我正在尝试运行两个操作:
- 从包含一些 ID(生成文件名)的 .txt 文件开始,检查该文件是否位于文件夹内;
- 如果步骤 1) 为 true,则将文件从该文件夹复制到指定文件夹。
.txt 文件存储如下代码:
111081
112054
112051
112064
这是我尝试过的:
from glob import glob
from shutil import copyfile
import os
input = 'C:/Users/xxxx/ids.txt'
input_folder = 'C:/Users/xxxx/input/'
dest_folder = 'C:/Users/xxxx/output/'
with open(input) as f:
for line in f:
string = "fixed_prefix_" + str(line.strip()) + '.asc'
if os.path.isfile(string):
copyfile(string, dest_folder)
string
变量生成以下内容(例如):
print string
fixed_prefix_111081.asc
然后,我确信搜索和将文件复制到目标文件夹时还存在其他问题。主要问题是我不知道如何在 input_folder
中搜索 fixed_prefix_111081.asc
文件。
最佳答案
copyfile
需要文件名作为目标。传递现有目录是行不通的情况。使用copy
可以处理两种情况(目标目录或目标文件)- 输入文件似乎在没有路径的情况下传递。如果您不在
input_folder
中,则必须生成完整的文件名,否则os.path.isfile
将始终为False
我的修复建议:
with open(input) as f:
for line in f:
string = "fixed_prefix_{}.asc".format(line.strip())
fp_string = os.path.join(input_folder,string)
if os.path.isfile(fp_string):
copy(fp_string, dest_folder)
关于python - 将数千个文件(按名称过滤)复制到指定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348863/