gpt4 book ai didi

python - 为什么我无法使用 ubuntu 在 for 循环 python 之后读取文件

转载 作者:行者123 更新时间:2023-11-30 23:43:43 25 4
gpt4 key购买 nike

由于某种原因,在 for 循环之后我无法读取输出文本文件。例如:

for line in a:
name = (x)
f = open('name','w')
for line in b:
get = (something)
f.write(get)
for line in c:
get2 = (something2)
f.write(get2)

(the below works if the above is commented out only)

f1 = open(name, 'r')
for line in f1:
print line

如果我注释掉循环,我就可以读取文件并打印内容。

我对编码非常陌生,并且猜测这是我明显缺少的东西。但是我似乎无法弄清楚。我用过谷歌,但读得越多,我就越觉得我错过了一些东西。如有任何建议,我们将不胜感激。

最佳答案

@bernie 在上面的评论中是正确的。问题是,当你执行 open(..., 'w') 时,文件被重写为空白,但 Python/操作系统实际上并没有写出你的内容 写入磁盘,直到缓冲区填满或调用 close()。 (这种延迟有助于加快速度,因为写入磁盘的速度很慢。)您还可以调用 flush() 来强制执行此操作,而无需关闭文件。

bernie 提到的 with 语句如下所示:

 with open('name', 'w') as f:
for line in b:
b.write(...)
for line in c:
b.write(...)
# f is closed now that we're leaving the with block
# and any writes are actually written out to the file

with open('name', 'r') as f:
for line in f:
print line

如果您使用的是 Python 2.5,而不是 2.6 或 2.7,则必须在文件顶部执行 from __future__ import with_statement

关于python - 为什么我无法使用 ubuntu 在 for 循环 python 之后读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10612375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com