2012-03-19 123 views
-4

我的文本文件有大約100行,我想遍歷它們並將引號添加到第一個值。但是,它只能遍歷第1行,並且不會通過我的100行的其餘部分。有人能幫我嗎?蟒蛇循環列表

line2List = [] 

    while True: 
     line2 = compFile.readline() 
     if line 2 == "": 
     break 
     line2List.append(line2) 
     s = line2List[0] 
     s = '""' + s 
+0

請發表您的所有代碼。 – Blender 2012-03-19 03:28:42

+0

發佈的代碼具有語法錯誤(如Blender所述)並且與描述不符。應該做些什麼?('在這個位置)? – 2012-03-19 06:33:50

回答

0

這看起來並不像它會做什麼都好:

if line 2 == "": 

你的意思是:

if line2 == "": 
1

嘗試

line2List = [] 

while True: 
    line2 = compFile.readline() 
    if line2 == "": # REMOVED SPACE 
    break 
    line2List.append('""' + line2) 
+0

謝謝。這適用於我需要的! – pythonNoob123 2012-03-19 07:37:43

+0

@ pythonNoob123如果答案是你正在尋找的你應該接受它,它給你增加了聲望,它給了那些花時間回覆聲望的人,並且它幫助未來的人立即找到最好的答案。 – austin1howard 2012-03-19 20:48:17

0

不知道你是什麼真的很想 - 也許這樣可以接受:

lines = open(filename).readlines() 

with open(filename, 'w') as f: 
    for x in (y for y in lines if y.strip()):  
     f.write('""' + x + '\n')