2012-02-05 66 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