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

2024-05-14 15:34:23 发布

您现在位置: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))

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


Tags: pathinimportsourceosdirfilenamefile
2条回答

一个简单的函数就可以做到这一点:

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\u folder=源文件夹的完整/相对路径

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

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

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

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

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))

相关问题 更多 >

    热门问题