无法将具有相似名称的多个文本文件合并到一个文件中
Cannot merge various text files with similar names into one file
我有一个问题,我遍历文件夹并想合并包含特定名称的文件。我有像 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)
试试这个:
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()
我有一个问题,我遍历文件夹并想合并包含特定名称的文件。我有像 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)
试试这个:
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()