Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我使用ubuntu读取python循环后的文件吗_Python_Printing_For Loop_Readfile - Fatal编程技术网

为什么可以';我使用ubuntu读取python循环后的文件吗

为什么可以';我使用ubuntu读取python循环后的文件吗,python,printing,for-loop,readfile,Python,Printing,For Loop,Readfile,由于某种原因,在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(nam

由于某种原因,在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在上面的评论中是正确的。问题是,当您执行
打开(…,'w')
时,文件被重写为空白,但Python/OS实际上不会将您
写入的内容写入磁盘,直到其缓冲区填满或调用
关闭()
。(此延迟有助于加快速度,因为写入磁盘的速度很慢。)您还可以调用
flush()
强制执行此操作,而无需关闭文件

bernie提到的带有
语句的
如下所示:

 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,那么您必须使用文件顶部的
语句从uuu future uuu导入

确保在完成编写后
.close()
文件。更好的方法是:使用上下文管理器(
with
语句),在
with
块结束时为您关闭文件;另外,异常是免费处理的。至少,您需要刷新正在写入的文件。您确定已正确粘贴代码吗?您的
f=open('name','w')
行发生在for循环中,因此每次执行循环时都会重新分配它,您将得到最后一次执行循环时的任何f。同意,您可能正在尝试打开并写入多个文件吗?否则我一辈子都想不出name变量的用途。字符串
'name'
与变量
name
不一样,这似乎是因为我没有关闭文件。马吕斯-你是对的,我抄错了。我实际上是在使用name创建一个XML文件中的输出文件名,该文件一直在变化。我知道还有更好的方法,但我只是还不知道。非常感谢大家的帮助。在这种情况下,使用with比for循环更好吗?什么才算是更好的编码?
使用
更好,这是Bernie引用的原因,但它根本不允许您放弃
for
循环。