我想寫一個Python腳本,使用屬於我工作的公司的特定外部應用程序。在編程和腳本編寫方面,我通常可以爲自己弄清楚這些事情,但是這次我真的很失落!雖然循環不執行主要功能
我似乎無法弄清楚爲什麼while循環不會正常工作。它不會給出任何不幫助我的錯誤。它似乎跳過循環中心的代碼的重要部分,然後繼續增加「計數」,就像之後應該那樣!
f = open('C:/tmp/tmp1.txt', 'w') #Create a tempory textfile
f.write("TEXTFILE\nTEXTFILE\nTEXTFILE\nTEXTFILE\nTEXTFILE\nTEXTFILE\n") #Put some simple text in there
f.close() #Close the file
count = 0 #Insert the line number from the text file you want to begin with (first line starts with 0)
num_lines = sum(1 for line1 in open('C:/tmp/tmp1.txt')) #Get the number of lines from the textfile
f = open('C:/tmp/tmp2.txt', 'w') #Create a new textfile
f.close() #Close it
while (count < num_lines): #Keep the loop within the starting line and total number of lines from the first text file
with open('C:/tmp/tmp1.txt', 'r') as f: #Open the first textfile
line2 = f.readlines() #Read these lines for later input
for line2[count] in f: #For each line from chosen starting line until last line from first text file,...
with open('C:/tmp/tmp2.txt', 'a') as g: #...with the second textfile open for appending strings,...
g.write("hello\n") #...write 'hello\n' each time while "count" < "num_lines"
count = count + 1 #Increment the "count"
我覺得一切正常,直到:「對於F中的2號線[計數]:」
我工作的實際代碼稍微複雜一些,並且應用程序我使用ISN」 t完全是爲了共享,所以我簡化了代碼來給愚蠢的輸出,而不是爲了解決問題。
我不在尋找替代代碼,我只是尋找一個爲什麼循環不工作的原因,所以我可以嘗試自己修復它。
所有的答案將不勝感激,並感謝大家提前!
科馬克
你可以使用'for line [count] in f:'?你有沒有嘗試'在f:'行? – Wug 2012-07-06 14:32:49
呵呵。你的問題是''read'()'調用後'f'沒有更多的行要讀,所以它在'line2 [count]'中放置了一個'None'(關於之前的內容)。 – cha0site 2012-07-06 14:33:30
它可能與在f中使用'line2 [count]有關。如果你創建了line2,你應該在line2中使用'for line:'。 – purpleladydragons 2012-07-06 14:35:47