这是我从以前的代码修改的代码。但是,我收到了这个错误:
TypeError: must be str not list in f1.write(head)
Run Code Online (Sandbox Code Playgroud)
这是产生此错误的代码部分:
from itertools import islice
with open("input.txt") as myfile:
head = list(islice(myfile, 3))
f1.write(head)
f1.close()
Run Code Online (Sandbox Code Playgroud)
好吧,你说得对,使用islice(filename, n)会让你得到nfile的第一行filename。这里的问题是当您尝试将这些行写入另一个文件时。
该错误非常直观(我已经添加了在这种情况下收到的完整错误):
TypeError: write() argument must be str, not list
Run Code Online (Sandbox Code Playgroud)
这是因为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)
Run Code Online (Sandbox Code Playgroud)
诚然,列表的内容是所有类型的str这个作品就像一个魅力; 如果没有,您只需要在调用中将每个循环包装item在for循环中,str()以确保将其转换为字符串。
如果您想要一种不需要循环的方法,您可以随时考虑使用f.writelines()代替f.write()(并且,查看 Jon 的评论以获取另一个使用 的提示writelines)。