2012-12-22 58 views
0

這很簡單,但我似乎無法正確理解。Python - 從文件讀入列表

我有一個包含在表單

0 1 2 
3 43 
5 6 7 8 

和這些數字的文本文件。

我想讀取這些數字並將其存儲在列表中,以便每個數字都是列表中的一個元素。如果我將整個文件作爲字符串讀取,我如何拆分字符串以將這些元素分開?

謝謝。

+0

是否要將數字存儲爲整數或字符串? – vkontori

+0

我不認爲正則表達式標籤適用於此... – vkontori

+0

愚蠢的標記已被修復。 –

回答

3

您可以通過該文件對象迭代就好像它是行的列表:

with open('file.txt', 'r') as handle: 
    numbers = [map(int, line.split()) for line in handle] 

稍微簡單的例子:

with open('file.txt', 'r') as handle: 
    for line in handle: 
     print line 
+0

哇。從來沒有見過這種語法! – ApproachingDarknessFish

0

首先打開文件。然後迭代文件對象以獲取其每一行並在該行上調用split()以獲取字符串列表。然後將列表中的每個字符串轉換爲數字:

f = open("somefile.txt") 

nums = [] 
strs = [] 

for line in f: 
    strs = line.split() #get an array of whitespace-separated substrings 
    for num in strs: 
     try: 
      nums.append(int(num)) #convert each substring to a number and append 
     except ValueError: #the string cannot be parsed to a number 
      pass 

nums現在包含文件中的所有數字。