簡體   English   中英

Python-將文本寫入文件?

[英]Python- Writing text to a file?

我正在嘗試學習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

為什么輸出有差異?

只有一種類型的文件對象,只有兩種不同的方法來創建一個。 主要區別在於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM