我想使用 readlines() 方法讀取記事本檔案。
f = open('/home/user/Desktop/my_file', 'r')
print(f.readlines())
輸出是:
['Hello!\n', 'Welcome to Barbara restaurant. \n', 'Here is the menu. \n']
如您所見,輸出中也會提到換行符。我應該怎么辦?請注意,我想使用 readlines() 方法。
PS!我的作業系統是 Linux Ubuntu,這是我的檔案的鏈接。
https://drive.google.com/file/d/1baVVxZjXmFwo_3uwdUCsrwHOG-Dlfo38/view?usp=sharing
我想得到下面的輸出:
Hello!
Welcome to Barbara restaurant.
Here is the menu.
uj5u.com熱心網友回復:
更新(因為您需要readlines()方法)
f = open('/home/user/Desktop/my_file', 'r')
for line in f.readlines():
print(line, end='')
輸出
Hello!
Welcome to Barbara restaurant.
Here is the menu.
原來的
您可以閱讀然后拆分每一行
f = open('/home/user/Desktop/my_file', 'r')
print(f.read().splitlines())
輸出
['你好!','歡迎來到芭芭拉餐廳。', '這是選單。']
uj5u.com熱心網友回復:
一種流水線式方法,可根據需要在每條線上進行一次。這可能對記憶體更友好,但缺點是更復雜。
f = open('/home/user/Desktop/my_file', 'r')
lines_iter = map(str.strip, f) # note you can only go through this once!
lines = list(lines_iter) # optional: move everything to a list
f.close() # don't forget to close - but only AFTER using the map object
輸出 -
>>> print(lines)
['Hello!', 'Welcome to Barbara restaurant.', 'Here is the menu.']
>>> print("\n".join(lines))
Hello!
Welcome to Barbara restaurant.
Here is the menu.
根據使用情況,您不需要將其移動到串列中。但是檔案物件需要可訪問,直到地圖物件對其進行處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517669.html
上一篇:找不到Microsoft.Maui.Controls.MapsNuGet包
下一篇:打開一個xlsx檔案
