![](/img/trans.png)
[英]How to read all .txt files in a folder and append its contents into one .txt file, using Python?
[英]Python: how to combine two .txt files into one and self-generate its .txt file
我想将两个 .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)
我使用此代码,它可以将两者结合起来并写入输出,但问题是它不是自动生成的文件,我们必须亲自创建一个输出文件
这非常有效 - 如果您愿意,只需更改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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.