簡體   English   中英

在 Python 中讀取文件並打印出來

[英]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保存在與 .py文件 cwd 相同的目錄中,或者將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.

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