2017-02-17 102 views
-2

我有一個文件說input.txt其中包含下列格式的數據::在Python中讀取文件的數據?

[8, 3, 4, 14, 19, 23, 10, 10, "Delhi"] 
13 
"Delhi" 

8 
10 
19 

我怎麼能看在Python或Ruby的數據。我可以看到我的第一行包含包含整數和字符串的數據。 而且我該如何儲存它?

+0

對於第一行,我應該將哪個數據結構se存儲整數和字符串數據類型? –

+1

http://stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python看到這個。它有助於你 –

回答

1

我給你舉個例子:

with open(fname) as f: 
    content = f.readlines() 
# you may also want to remove whitespace characters like `\n` at the end of each line 
content = [x.strip() for x in content] 

注:列表:內置的Python序列。儘管它的名字更像 到其他語言的數組而不是鏈接列表,因爲對 元素的訪問是O(1)。

+0

你需要更多的細節看到這個http://stackoverflow.com/questions/10393176/is-there-a-way-to-read-a-txt-file-and-store-each-line-to-memory –

1

如果你信任你的輸入文本文件的來源,那麼我注意到,每一行是一個有效的Python表達式,所以你可以這樣做:

with open(filename) as txt: 
    evaluated_lines = [eval(line) for line in txt if line.strip()] 
print(evaluated_lines) 

輸出:

[[8, 3, 4, 14, 19, 23, 10, 10, 'Delhi'], 13, 'Delhi', 8, 10, 19] 

請注意,Python列表數據類型可以包含子列表,整數和字符串的混合