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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17749058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:04:56  来源:igfitidea点击:

combine multiple text files into one text file using python

python

提问by

suppose we have many text files as follows:

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

file1:

文件 1:

abc
def
ghi

file2:

文件2:

ABC
DEF
GHI

file3:

文件 3:

adfafa

file4:

文件 4:

ewrtwe
rewrt
wer
wrwe

How can we make one text file like below:

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

result:

结果:

abc
def
ghi
ABC
DEF
GHI
adfafa
ewrtwe
rewrt
wer
wrwe

Related code may be:

相关代码可能是:

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?

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

采纳答案by apiguy

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

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

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())

回答by Robert Caspary

You could try something like this:

你可以尝试这样的事情:

import glob
files = glob.glob( '*.txt' )

with open( 'result.txt', 'w' ) as result:
    for file_ in files:
        for line in open( file_, 'r' ):
            result.write( line )

Should be straight forward to read.

应该直接阅读。

回答by llb

The fileinputmodule is designed perfectly for this use case.

fileinput模块专为此用例而设计。

import fileinput
import glob

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

with open('result.txt', 'w') as file:
    input_lines = fileinput.input(file_list)
    file.writelines(input_lines)

回答by proma

filenames = ['resultsone.txt', 'resultstwo.txt']
with open('resultsthree', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

回答by Sadheesh

It is also possible to combine files by incorporating OS commands. Example:

还可以通过合并操作系统命令来组合文件。例子:

import os
import subprocess
subprocess.call("cat *.csv > /path/outputs.csv")