我有2个文本文件,例如['file1.txt','file2.txt']。我想编写一个Python脚本来将这些文件连接成一个新文件,使用open()等基本函数打开每个文件,通过调用f.readline()逐行读取,并使用f将每一行写入该新文件。写()。我是python中文件处理编程的新手。有人可以帮我这个吗?
答案 0 :(得分:5)
回复是already here:
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
你需要什么(根据评论),是一个只有2行的文件。在第一行,第一个文件的内容(没有断行)和第二行的第二个文件的内容。所以,如果你的文件很小(每个文件小于1MB,可能会占用大量内存......)
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
content = infile.read().replace('\n', '')
outfile.write(content)
答案 1 :(得分:2)
f1 = open("file1.txt")
f1_contents = f1.read()
f1.close()
f2 = open("file2.txt")
f2_contents = f2.read()
f2.close()
f3 = open("concatenated.txt", "w") # open in `w` mode to write
f3.write(f1_contents + f2_contents) # concatenate the contents
f3.close()
如果您不熟悉Python,那么UNIX cat
命令就是这样:连接多个文件的内容。
如果要在两个文件之间换行,请将倒数第二行更改为f1_contents + "\n" + f2_contents
。 (\n
表示新行)。