我遇到一个问题,在该文件夹中进行迭代,并希望合并包含特定名称的文件。我有类似1a_USR02.txt,1b_USR02.txt和1a_USR06、1b_USR06的文件。但是,当我使用以下代码时,最终文件FINAL_USR02或FINAL_USR06仅包含第二个文件(1b_USR02或1b_UR06)。有什么想法吗?
import os
import shutil
cwd = os.getcwd()
directory = (cwd + '\\FINAL' + '\\')
delheadfiles = ['UST04', 'USR02', 'USR06','1251', 'AGRS', 'TEXTS',\
'USERS', 'FLAGS', 'DEVACCESS', 'USERNAME', 'TSTC', 'TSTCT']
for delheadfile in delheadfiles:
for file in os.listdir(directory):
if file.endswith(delheadfile + ".txt"):
table04 = (directory + 'FINAL_' + delheadfile + '.txt')
with open(directory + file, 'rb') as readfile:
if file.endswith(delheadfile + ".txt"):
with open(table04, 'wb') as outfile:
shutil.copyfileobj(readfile, outfile)
答案 0 :(得分:1)
尝试一下:
import os
files_extensions = ['UST04', 'USR02', 'USR06']
folder_files = os.listdir()
for extension in files_extensions:
with open('FINAL_' + extension + '.txt', 'a+') as out_file:
for item in folder_files:
if item.endswith(extension + '.txt'):
data = open(item, 'r').read()
out_file.write(data)
out_file.close()