使用python将多个文本文件合并为一个文本文件

问题描述:

假设我们有很多文本文件如下:

suppose we have many text files as follows:

文件 1:

abc
def
ghi

文件 2:

ABC
DEF
GHI

文件 3:

adfafa

文件 4:

ewrtwe
rewrt
wer
wrwe

我们如何制作一个如下所示的文本文件:

How can we make one text file like below:

结果:

abc
def
ghi
ABC
DEF
GHI
adfafa
ewrtwe
rewrt
wer
wrwe

相关代码可能是:

import csv
import glob
files = glob.glob('*.txt')
for file in files:
with open('result.txt', 'w') as result:
result.write(str(file)+'\n')

在这之后?有什么帮助吗?

After this? Any help?

可以像这样直接将每个文件的内容读入输出文件句柄的write方法中:

You can read the content of each file directly into the write method of the output file handle like this:

import glob

read_files = glob.glob("*.txt")

with open("result.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())