Python移动文件脚本:如何实现文件名包含/部分匹配?
问题:修改Python文件移动脚本实现文件名包含匹配
原脚本通过startswith匹配文件名开头来移动文件,现在需要改为匹配文件名中包含指定内容(如客户号、合同号),且不能用contains方法,该如何修改?
原脚本代码:
import os import shutil ################# MOVE FILES SCRIPT ############################ # Moving files from one folder to another based on file names starting or ending with input # Step 1: Source Directory / Folder movefrom_path = input('Enter the move from path of the directory:') # Step 2: Destination Directory / Folder moveto_path = input("Enter the move to path of the directory:") # Step 3: Create folder if it doesn't exist if not os.path.exists(moveto_path): os.makedirs(moveto_path) # Step 4: What is the name or number we are trying to match (I was searchinng contract number) filename_match = input("Enter characters of type of file you want to move:") # Not working: Does the file start or end with name number we are trying to match # starts_ends = input("Enter 'startswith' or 'endswith' with file name match you just entered:") # Step 5: List all the files in directory with os entries = os.listdir(movefrom_path) # Step 6: Run iterate 'for' 'in' loop for entry in entries: # could also you 'startwith' if file name starts instead of ends with input from filename_match if entry.startswith(filename_match): shutil.move(movefrom_path + entry, moveto_path) print('Done.')
解决方案
直接使用Python的**成员运算符in**即可实现包含匹配,无需依赖contains方法,同时优化路径拼接避免潜在错误:
修改后的完整代码:
import os import shutil ################# MOVE FILES SCRIPT ############################ # Moving files from one folder to another based on file names containing the input string # Step 1: Source Directory / Folder movefrom_path = input('Enter the move from path of the directory:') # Step 2: Destination Directory / Folder moveto_path = input("Enter the move to path of the directory:") # Step 3: Create folder if it doesn't exist if not os.path.exists(moveto_path): os.makedirs(moveto_path) # Step 4: What is the name or number we are trying to match (e.g., contract number) filename_match = input("Enter characters of type of file you want to move:") # Step 5: List all the files in directory with os entries = os.listdir(movefrom_path) # Step 6: Iterate through files and move matches for entry in entries: # Check if the target string is contained anywhere in the filename if filename_match in entry: # Use os.path.join to safely concatenate paths (avoids missing slashes issues) source_full_path = os.path.join(movefrom_path, entry) shutil.move(source_full_path, moveto_path) print('Done.')
关键修改说明:
- 匹配逻辑变更:将
entry.startswith(filename_match)替换为filename_match in entry,只要文件名中包含输入的匹配字符串,就会执行移动操作。 - 路径拼接优化:用
os.path.join()替代直接字符串拼接路径,自动处理不同操作系统的路径分隔符,避免因路径末尾缺少斜杠导致的文件路径错误。
内容的提问来源于stack exchange,提问作者LakeConstanceCH
相关产品推荐
相关产品推荐

