2013-07-21 94 views
-4

我有一個文本文件,其中包含以下信息: ['123','456','789'] 我想從每個文件中讀取它們作爲單獨的整數時間。例如,第一次得到123作爲整數,第二次得到456整數,...如何從文本文件中讀取字符串

什麼是最簡單的方法呢?謝謝!

+0

你在一個文件中只有一行包含這個? –

回答

7

你可以這樣做:

with open('file.txt') as myfile: 
    info = myfile.readline() 

注意,名單將是一個字符串,而不是一個列表對象。將其轉換爲一個列表,你可以使用ast.literal_eval

import ast 
info = ast.literal_eval(info) 

現在用一個簡單的循環:

for i in info: 
    print int(i) 

打印:

123 
456 
789 
+0

非常感謝! – Tom

+0

@Tom不客氣!不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work):) – TerryA

0

嘗試:

from ast import literal_eval 
with open('file') as fin: 
    for number in map(int, literal_eval(next(fin, '[]'))): 
     print number 
+0

非常感謝! – Tom

1

簡單地做:

f = open("file.txt", "r")   //Opens the file and stores it in a variable 

for line in f:      //It says; for every line in the file f, do following: 
     line = int(line)   //converts the variable 'line' to an int 
     print(line)     //prints the variable 

如果你想確保變量「行」是數據類型爲int的 您可以在print(type(line))擠代碼

輸出:

123 
456 
789 

=)我確定這是最簡單的方法!

+0

非常感謝! – Tom

相關問題