首页 > 解决方案 > 调用 f.write() 后文件仍然为空

问题描述

这个程序(用 Python 编写)应该只显示写入特定文件的前两行文本。但是,当我运行它时,虽然它没有错误,但它不会在 IDE 和文件本身中显示任何输出。

def file_read_from_head(fname, nlines):
    from itertools import islice
    with open(fname) as f:
        for line in islice(f, nlines):
            print(line)


f = open('test.txt', 'w')
f.write = ("Hello welcome to Python \n"
           "THis is the second line \n"
           "This is the third line \n")


print(file_read_from_head('test.txt', 2))

标签: pythonoutput

解决方案


几点注意事项:

  1. 如注释中所示,您应该调用 f.write()而不是 将输出分配给名为的变量f.write
  2. 在您致电后,f.write()您还需要关闭该文件。您可以使用f.close(). 但是,使用上下文管理器是更好的做法(请参阅此答案下方的评论)。使用上下文管理器可以更轻松地避免错误(例如忘记关闭文件......)。您实际上已经在file_read_from_head()函数中使用了上下文管理器。
  3. 您的函数file_read_from_head()调用print(line),因此print(file_read_from_head())不需要(也没有按照您的意图进行)
  4. 在函数导入通常被认为是不好的做法(请参阅此问题进行讨论)。相反,它更喜欢将所有导入语句放在文件的顶部。

考虑到以上所有因素,我们可以将您的代码修改为:

from itertools import islice

def file_read_from_head(fname, nlines):
    with open(fname) as f:
        for line in islice(f, nlines):
            print(line)


# Context managers make it easier to avoid forgetting to close files
with open('test.txt', 'w') as f:
    f.write("Hello welcome to Python \n"
            "This is the second line \n"
            "This is the third line \n")


file_read_from_head('test.txt', 2)

推荐阅读