簡體   English   中英

為python寫輸出不起作用

[英]writing output for python not functioning

我正在嘗試輸出一個新的txt文件,但出現空白。 我正在做這個

my_file = open("something.txt","w")
#and then
my_file.write("hello")

在此行之后,它只說5,然后文件中沒有文本

我究竟做錯了什么?

您必須在刷新寫入之前關閉文件 如果我打開翻譯,然后輸入:

my_file = open('something.txt', 'w')
my_file.write('hello')

然后在文本程序中打開文件,沒有文本。

如果再發出:

my_file.close()

瞧! 文本!

如果您只想刷新一次並繼續寫入,也可以這樣做:

my_file.flush()
my_file.write('\nhello again')  # file still says 'hello'
my_file.flush()   # now it says 'hello again' on the next line

順便說一句,如果您碰巧讀了 file.write 精美文檔 ,它只有兩行,那么您將得到答案(強調我的意思):

將字符串寫入文件。 沒有返回值。 由於存在緩沖,在調用flush()或close()方法之前,字符串實際上可能不會顯示在文件中。

如果您不想關閉文件,請with使用:

with open("something.txt","w") as f: 
    f.write('hello')

然后python會自動為您關閉文件。

正如兩位煉金術士指出的,該文件必須關閉。 python文件編寫器使用緩沖區(我認為是BufferedIOBase ),這意味着在將它們批量寫入磁盤之前,它會收集一定數量的字節。 這樣做是為了在單個文件上執行大量寫操作時節省開銷。

另外:處理文件時,請嘗試使用with -environment的文件,以確保在完成寫入/讀取后關閉文件:

with open("somefile.txt", "w") as myfile:
    myfile.write("42")

# when you reach this point, i.e. leave the with-environment,
# the file is closed automatically.

python文件編寫器使用緩沖區(我認為是BufferedIOBase),這意味着在將它們批量寫入磁盤之前,它會收集一定數量的字節。 這樣做是為了在單個文件上執行大量寫操作時節省開銷。 引用@ m00am

您的代碼也沒問題。 只需添加一個用於關閉文件的語句,然后即可正常工作。

my_file = open("fin.txt","w")
#and then
my_file.write("hello")
my_file.close()

暫無
暫無

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

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