[英]Read File and Print It Out in Python
我是python的新手。 我想讀一個文件。 文件中的內容是:
17 2 3 0
5 16 11 7
9 8 0 6
0 14 17 1
我想像這樣閱讀並打印出來:
aList= [[17,2,3,0],
[5,16,11,7],
[9,8,0,6],
[0,14,17,1]]
這是我的代碼:
file = open("file.txt","r")
aList=[]
for line in file:
aList.append(line.strip().split(","))
現在錯誤是找不到文件,無法打印出來。
嘗試這個:
aList = []
with open('file.txt') as handle:
for text in handle:
aList.append(text.strip().split())
print(list(filter(None, aList)))
輸出是: [['17', '2', '3', '0'], ['5', '16', '11', '7'], ['9', '8', '0', '6'], ['0', '14', '17', '1']]
更短:
with open(filname,'r') as f:
print([line.split() for line in f if line.split()])
希望這有幫助:
flread=open('path/to/file/filename','r')
for i in flread.readlines():
for k in i.split(' '):
a.append(int(k))
a=[]
b.append(a)
print(b)
輸出: [[17, 2, 3, 0], [5, 16, 11, 7], [9, 8, 0, 6], [0, 14, 17, 1]]
文件路徑將相對於您的
python 腳本(
當前工作目錄。 您需要將.py
文件)
file.txt
保存在與
cwd 相同的目錄中,或者將.py
文件
file.txt
的絕對路徑用於open()
函數,例如open('/path/to/your/file.txt')
(假設您運行的是 Linux)或open('C:\\\\path\\\\to\\\\your\\\\file.txt')
(windows)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.