Python:如何将两个.txt文件合并为一个并自行生成其.txt文件

时间:2019-03-19 19:45:20

标签: python

我想将两个.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)  

我使用此代码将它们结合起来并写入输出,但是问题是它不是自动生成的文件,我们必须亲自创建输出文件

2 个答案:

答案 0 :(得分:1)

这非常好用-如果需要,只需更改file1.txtfile2.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)