Python:如果指定路径中的文件名包含字符串,则移动到文件夹



这里是python的新手。我想创建一个脚本来扫描我的目录,如果文件名中包含某个字符串,那么它将自动移动到我选择的文件夹中。尝试过这个,但没有运气:

import os
import shutil
import fnmatch
import glob
ffe_path = 'E:/FFE'
new_path = 'E:/FFE/Membership/letters'
keyword = 'membership'

os.chdir('E:/FFE/Membership')
os.mkdir('letters')

source_dir = 'E:/FFE'
dest_dir = 'E:/FFE/Membership/letters'
os.chdir(source_dir)
for top, dirs, files in os.walk(source_dir):
for filename in files:
if not filename.endswith('.docx'):
continue
file_path = os.path.join(top, filename)
with open(file_path, 'r') as f:
if '*membership' in f.read():
shutil.move(file_path, os.path.join(dest_dir, filename))

如有任何见解,我们将不胜感激。

一个简单的函数就能完成任务:

def copyCertainFiles(source_folder, dest_folder, string_to_match, file_type=None):
# Check all files in source_folder
for filename in os.listdir(source_folder):
# Move the file if the filename contains the string to match
if file_type == None:
if string_to_match in filename:
shutil.move(os.path.join(source_folder, filename), dest_folder)
# Check if the keyword and the file type both match
elif isinstance(file_type, str):
if string_to_match in filename and file_type in filename:
shutil.move(os.path.join(source_folder, filename), dest_folder)

source_folder=源文件夹的完整/相对路径

dest_folder=目标文件夹的完整/相对路径(需要事先创建(

string_to_match=将复制文件的字符串基础

file_type(可选(=如果只应移动特定的文件类型。

当然,您可以通过设置忽略大小写的参数、在不存在目标文件夹的情况下自动创建目标文件夹、在没有指定关键字的情况下复制特定文件类型的所有文件等等,使此函数变得更好。此外,您还可以使用正则表达式来匹配文件类型,这将更加灵活。

f.read读取文件。您很可能不想查看字符串是否在文件的内容中。我修复了你的代码以查看文件名:

import os
import shutil
import fnmatch
import glob
ffe_path = 'E:/FFE'
new_path = 'E:/FFE/Membership/letters'
keyword = 'membership'

os.chdir('E:/FFE/Membership')
os.mkdir('letters')

source_dir = 'E:/FFE'
dest_dir = 'E:/FFE/Membership/letters'
os.chdir(source_dir)
for top, dirs, files in os.walk(source_dir):
for filename in files:
if not filename.endswith('.docx'):
continue
file_path = os.path.join(top, filename)
if '*membership' in filename:
shutil.move(file_path, os.path.join(dest_dir, filename))

相关内容

最新更新