簡體   English   中英

python 代碼不打印文本文件“c”

[英]The python code does not prints the text file 'c'

該代碼不返回文本文件的內容,而是一個空字符串

a = open('myfile.txt', 'w+')
list01 = ['content from list 01 ~']
list02 = ['content from list 02 ']
a.writelines(list01)
a.writelines(list02)
b = open('myfile.txt', 'r+')
c = b.readline()
print("This is c: ", c)

writelines不會有效地寫入文件,它會一直保留在緩沖區中,直到您調用closeflush ,使用with語句輕松完成此操作,該語句在文件末尾自動關閉文件

with open('myfile.txt', 'w') as a:
    list01 = ['content from list 01 ~']
    list02 = ['content from list 02 ']
    a.writelines(list01)
    a.writelines(list02)

with open('myfile.txt', 'r') as b:
    c = b.readline()

print("This is c: ", c)

還使用wr ,刪除您不需要的+參考文件模式

您的代碼只需進行一些更改即可工作。

而不是w+使用r+ r+用於讀寫。 無需再次打開文件進行閱讀。 你可以說c = a.readline()

a = open('myfile.txt', 'r+')
list01 = ['content from list 01 ~']
list02 = ['content from list 02 ']
a.writelines(list01)
a.writelines(list02)
c = a.readline()
print("This is c: ", c)

暫無
暫無

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

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