我想将两个.txt文件合并为另一个自行生成的.txt文件
示例:-
文件1的内容
abcdefg
文件2的内容
123456
输出文件夹中的自生成.txt文件
abcdefg
123456
filenames = [fname1, fname2, fname3]
with open('H:\output\output.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
我使用此代码将它们结合起来并写入输出,但是问题是它不是自动生成的文件,我们必须亲自创建输出文件
答案 0 :(得分:1)
这非常好用-如果需要,只需更改file1.txt
和file2.txt
行以适合两个文件的文件名:
# Open both .TXT files
file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")
# Read both .TXT files and put contents into variables
file1Contents = file1.read()
file2Contents = file2.read()
# Close both files
file1.close()
file2.close()
# Open new .TXT file for the resulting concatenated file
resultFile = open("result.txt","w")
# Write concatenated contents to resulting file
resultFile.write(file1Contents + file2Contents)
# Close resulting file
resultFile.close()
答案 1 :(得分:-1)
回答我自己的问题。
引荐的here
#Entering file names
filenames = [fname1, fname2, fname3]
#Wriring it into a new file
with open('output.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)