将多个文件合并到新的fi

2024-05-09 18:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件,比如['file1.txt','file2.txt']。我想编写一个Python脚本将这些文件连接到一个新文件中,使用open()等基本函数打开每个文件,通过调用f.read line()逐行读取,并使用f.write()将每一行写入该新文件。我是python中的文件处理编程新手。有人能帮我吗?


Tags: 文件函数txt脚本read编程lineopen
2条回答

响应是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)

扁平线溶液

你需要的(根据评论),是一个只有两行的文件。在第一行,第一个文件的内容(没有换行符),在第二行,第二个文件。所以,如果你的文件很小(每个文件小于~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)
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表示新行)。

相关问题 更多 >