Python 移动文件脚本,'startswith' 和 'endswith',但是,如何根据用户输入查找包含或部分匹配

问题描述 投票:0回答:1

我有以下脚本

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

但是,在步骤 6 中,我想根据“包含”搜索文件名,而不仅仅是“startswith”或“endswith”。如何让 for in 循环根据文件名中的匹配进行迭代,例如356333(客户编号、合同编号等)。 我无法将“startsWith”或“endsWith”替换为“contains”

python move contains
1个回答
0
投票

如果条目中的文件名匹配:

而不是

如果entry.startswith(filename_match):

完美解决我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.