2012-06-20 101 views
0
datafile = open("temp.txt", "r") 
record = datafile.readline() 

while record != '': 
    d1 = datafile.strip("\n").split(",") 
    print d1[0],float (d1[1]) 
    record = datafile.readline() 

datafile.close() 

臨時文件包含蟒蛇文本閱讀

a,12.7 
b,13.7 
c,18.12 

我不能輸出。請幫忙。

+0

您是否收到任何錯誤? – SomeKittens

回答

1

您文件處理操作,但應該工作上線

這樣D1 = record.strip( 「\ n」)。分裂( 「」)

datafile = open("temp.txt", "r") 
record = datafile.readline() 

while record != '': 
    d1 = record.strip("\n").split(",") 
    print d1[0],float (d1[1]) 
    record = datafile.readline() 

datafile.close() 
2

你想調用條和拆分線上,而不是文件。

更換

d1 = datafile.strip("\n").split(",")

隨着

d1 = record.strip("\n").split(",")

4

正確的代碼應該是:

with open('temp.txt') as f: 
    for line in f: 
     after_split = line.strip("\n").split(",") 
     print after_split[0], float(after_split[1]) 

你沒有得到輸出的主要原因在你的代碼那datafile沒有strip()方法,我很驚訝你沒有收到異常。

我強烈建議你閱讀Python的教程 - 它看起來像你想Python寫在另一種語言,那就是個好東西

+0

感謝您的建議..真的,我需要更多的教程.. –

0

Perhap s以下將更好地爲您工作(評論作爲解釋):

# open file this way so that it automatically closes upon any errors 
with open("temp.txt", "r") as f: 
    data = f.readlines() 

for line in data: 
    # only process non-empty lines 
    if line.strip(): 
     d1 = line.strip("\n").split(",") 
     print d1[0], float(d1[1]) 
+0

通常最好不要將文件的內容讀入內存。 Jon Clements更高效。與文本文件相關的文件對象自然支持迭代。 – pepr

+0

很高興知道,謝謝! – mVChr