如何读取文本文件的前 N ​​行并将其写入另一个文本文件?

How to read first N lines of a text file and write it to another text file?

这是我修改之前代码的代码。 但是,我得到了这个错误:

TypeError: must be str not list in f1.write(head)

这是产生此错误的代码部分:

from itertools import islice
with open("input.txt") as myfile:
    head = list(islice(myfile, 3))
f1.write(head)

f1.close()  

嗯,你没看错,使用 islice(filename, n) 会得到文件 filename 的前 n 行。这里的问题是当您尝试将这些行写入另一个文件时。

错误非常直观(我已经添加了在这种情况下收到的完整错误):

TypeError: write() argument must be str, not list

这是因为 f.write() 接受字符串作为参数,而不是 list 类型。

因此,不要按原样转储列表,而是使用 for 循环将其内容写入其他文件:

with open("input.txt", "r") as myfile:
    head = list(islice(myfile, 3))

# always remember, use files in a with statement
with open("output.txt", "w") as f2:
    for item in head:
        f2.write(item)

假设列表的内容是 all 类型 str 这很有魅力;如果没有,您只需要在 str() 调用中将 for 循环中的每个 item 包装起来,以确保将其转换为字符串。

如果您想要一种不需要循环的方法,您总是可以考虑 使用 f.writelines() 而不是f.write()(并且,查看 Jon 的评论以获取 writelines 的另一个提示)。