Python连接文本文件我有20个文件名的列表,比如['file1.txt', 'file2.txt', ...]..我想编写一个Python脚本,将这些文件连接到一个新文件中。我可以打开每个文件f = open(...),通过调用读取行f.readline(),并将每一行写入新文件中。在我看来,这不太“优雅”,尤其是我不得不逐行读/写的部分。在Python中是否有一种更“优雅”的方法来做到这一点呢?
3 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
shutil.copyfileobj
.
with open('output_file.txt','wb') as wfd: for f in ['seg1.txt','seg2.txt','seg3.txt']: with open(f,'rb') as fd: shutil.copyfileobj(fd, wfd)
慕容708150
TA贡献1831条经验 获得超4个赞
import fileinputwith open(outfilename, 'w') as fout, fileinput.input(filenames) as fin: for line in fin: fout.write(line)
fileinput
with
close
fileinput
fileinput
with open('outfilename', 'w') as fout: fin = fileinput.input(filenames) for line in fin: fout.write(line) fin.close()
添加回答
举报
0/150
提交
取消