![](/img/trans.png)
[英]Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them
[英]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
不會有效地寫入文件,它會一直保留在緩沖區中,直到您調用close
的flush
,使用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)
還使用w
和r
,刪除您不需要的+
, 參考文件模式
您的代碼只需進行一些更改即可工作。
而不是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.