2016-01-31 109 views
2

我想學習python,並想寫一些文本到一個文件。我遇到了兩種文件對象。Python-將文本寫入文件?

FOUT =打開( 「的abc.txt」,一)

張開( 「的abc.txt」,a)根據FOUT:

以下代碼:

f= open("abc.txt", 'a') 
f.write("Step 1\n") 
print "Step 1" 
with open("abc.txt", 'a') as fout: 
    fout.write("Step 2\n") 

都給輸出:

Step 2 
Step 1 

以下代碼:

f= open("abc1.txt", 'a') 
f.write("Step 1\n") 
f= open("abc1.txt", 'a') 
f.write("Step 2\n") 

都給輸出:

Step 1 
Step 2 

爲什麼會出現在輸出區別?

回答

5

只有一種類型的文件對象,只有兩種不同的方法來創建一個。主要區別在於with open("abc.txt",a) as fout:這一行處理關閉文件,因此它不太容易出錯。

發生了什麼是您使用fout=open("abc.txt",a)語句創建的文件在程序結束時自動關閉,因此只能在後面進行附加操作。

如果您運行下面的代碼,你會看到它產生的輸出以正確的順序:

f = open("abc.txt", 'a') 
f.write("Step 1\n") 
f.close() 
with open("abc.txt", 'a') as fout: 
    fout.write("Step 2\n") 

原因線條變得逆轉是由於爲了使文件被關閉。您的第一個示例中的代碼與此類似:

f1 = open("abc.txt", 'a') 
f1.write("Step 1\n") 

# these three lines are roughly equivalent to the with statement (providing no errors happen) 
f2 = open("abc.txt", 'a') 
f2.write("Step 2\n") 
f2.close() # "Step 2" is appended to the file here 

# This happens automatically when your program exits if you don't do it yourself. 
f1.close() # "Step 1" is appended to the file here 
+0

謝謝。但爲什麼在輸出的差異呢? –

+0

我現在還在回答這個問題,我正在分步實施:) – Jezzamon

+0

哦!非常感謝!我無法涉及到文件的寫入與文件關閉的關係。你把它清理乾淨了!謝謝! –