30

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

文件1:

abc
def
ghi

文件2:

ABC
DEF
GHI

文件3:

adfafa

文件4:

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

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

4

5 回答 5

77

您可以将每个文件的内容直接读取到输出文件句柄的 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())
于 2013-07-19T14:59:59.697 回答
17

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)
于 2013-07-19T15:01:32.447 回答
8

你可以尝试这样的事情:

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 )

应该直接阅读。

于 2013-07-19T14:58:03.483 回答
2

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

import os
import subprocess
subprocess.call("cat *.csv > /path/outputs.csv")
于 2016-05-17T10:46:56.557 回答
0
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)
于 2015-06-04T16:20:14.343 回答