python - 调用 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))
解决方案
几点注意事项:
- 如注释中所示,您应该调用
f.write()
,而不是 将输出分配给名为的变量f.write
- 在您致电后,
f.write()
您还需要关闭该文件。您可以使用f.close()
. 但是,使用上下文管理器是更好的做法(请参阅此答案下方的评论)。使用上下文管理器可以更轻松地避免错误(例如忘记关闭文件......)。您实际上已经在file_read_from_head()
函数中使用了上下文管理器。 - 您的函数
file_read_from_head()
调用print(line)
,因此print(file_read_from_head())
不需要(也没有按照您的意图进行) - 在函数内导入通常被认为是不好的做法(请参阅此问题进行讨论)。相反,它更喜欢将所有导入语句放在文件的顶部。
考虑到以上所有因素,我们可以将您的代码修改为:
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)
推荐阅读
- python - 我的 Python 代码有多少个线程?
- django - 我们如何使用表格中的 django orm 使用单独列表中的值添加额外的字段?
- javascript - 我无法在事件处理程序中执行道具父方法
- tensorflow - 如何在 Tensorflow 中嵌入离散 ID?
- r - 如何创建随机附加行并将其附加到现有数据框中?
- html - 仅使用 CSS,显示 HTML5 元素内文本的最后 3 个字母
- python - 方法显示为数据属性
- testng - 在 TestNG 中断言测试用例的正确方法是什么?
- angular6 - 如何在 angular4 或更高版本中更改 mouseover 和 mouseleave 上的图像 src?
- java - 在复杂类上使用 JAXB 解组器时 AtomicInteger 递增