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

时间:2013-07-19 14:46:43

标签: python

假设我们有许多文本文件,如下所示:

file1:

abc
def
ghi

file2的:

ABC
DEF
GHI

file3的:

adfafa

file4将:

ewrtwe
rewrt
wer
wrwe

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

结果:

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

之后呢?有什么帮助吗?

5 个答案:

答案 0 :(得分:48)

您可以直接将每个文件的内容读入输出文件句柄的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())

答案 1 :(得分:8)

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)

答案 2 :(得分:6)

您可以尝试这样的事情:

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 )

应该直接阅读。

答案 3 :(得分:1)

还可以通过合并OS命令来组合文件。例如:

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

答案 4 :(得分:-1)

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)