2012-02-05 62 views
1

窗7,蟒2.7.2文件不关闭

以下运行的w/o错误:

from subprocess import call 

f = open("file1","w") 
f.writelines("sigh") 
f.flush 
f.close 
call("copy file1 + file2 file3", shell=True) 

然而,file3的只包含file2中的内容。文件1和文件2的名称都如同窗口的正常一样回显,但是在调用副本时,文件1显示为空。看起来好像file1还没有被完全写入和刷新。如果file1已单独创建,作为同一Python文件中的反对,如预期的那样运行如下:

from subprocess import call 
call("copy file1 + file2 file3", shell=True) 

很抱歉,如果蟒蛇newbieness这里要指责。许多thx任何协助。

回答

7

你缺少括号:

f.flush() 
f.close() 

你的代码是有效的语法,但不调用这两个函数。

甲更Python方式写该序列是:

with open("file1","w") as f: 
    f.write("sigh\n") # don't use writelines() for one lonely string 
call("copy file1 + file2 file3", shell=True) 

即会在with块的末尾自动关闭f(以及flush()是多余的反正)。

+0

/脸红谢谢你 – user1179088 2012-02-05 09:12:39