Python连接文本文件 [英] Python concatenate text files
问题描述
我有20个文件名的列表,如 ['file1.txt','file2.txt',...]
。我想编写一个Python脚本来连接这些文件到一个新的文件。我可以通过 f = open(...)
打开每个文件,通过调用 f.readline()
,并将每行写入该新文件。对我来说,这看起来不是很优雅,尤其是我必须阅读的部分//逐行写。
在Python中是否有更优雅的方式来实现这个功能?
对于大文件:
<$ p $打开('路径/到/输出/文件','W')作为outfile的文件名= ['file1.txt','file2.txt',...]
:
用于文件名中的fname:
以open(fname)作为infile:
用于infile中的行:
outfile.write(line)
$ c $对于小文件:
code> filenames = ['file1.txt','file2.txt',...]
打开('path / to / output / file','w')作为outfile:
为文件名中的fname:
以open(fname)作为infile:
outfile.write(infile.read())
...另一个我想到的有趣的:
filenames = ['file1.txt','file2.txt',...]
with open('path / to / output / file','w')as outfile:
for itertools.chain.from_iterable(itertools.imap(open,filnames)):
outfile .write(line)
不幸的是,这最后一个方法留下了一些打开的文件描述符,无论如何照顾。我只是觉得这很有趣。
I have a list of 20 file names, like ['file1.txt', 'file2.txt', ...]
. I want to write a Python script to concatenate these files into a new file. I could open each file by f = open(...)
, read line by line by calling f.readline()
, and write each line into that new file. It doesn't seem very "elegant" to me, especially the part where I have to read//write line by line.
Is there a more "elegant" way to do this in Python?
This should do it
For large files:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
For small files:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
… and another interesting one that I thought of:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
outfile.write(line)
Sadly, this last method leaves a few open file descriptors, which the GC should take care of anyway. I just thought it was interesting
这篇关于Python连接文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!