我正在尝试编写一个 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"
我认为一切正常,直到:“for line2[count] in f:”
我正在处理的实际代码要复杂一些,而且我使用的应用程序并不完全是为了共享,所以我简化了代码以提供愚蠢的输出,而不是仅仅为了解决问题。
我不是在寻找替代代码,我只是在寻找循环不起作用的原因,以便我可以尝试自己修复它。
所有答案将不胜感激,并提前感谢大家!
科马克