在For循环中丢失一行文本文件

-2 python

每次我一次读取一行时,我的For循环会跳过第一行.当我只需要将整个文件读入内存时,问题就不会发生,但大多数情况下我需要一次读取一行.

这是问题发生的一个例子.此循环只是重新排序列表中的元素.我省略了打开和关闭读写文件的行(我这样做的笨重方式).它的所有逗号分隔文本数据.

lineString=fileItemR.readline()

for lineString in fileItemR:
    lineList = lineString.split(",")
    newList = (lineList[1],lineList[0],lineList[2:99])
    lineItem = str(newList)
    formatString = lineItem.replace("('","").replace("', '",",").replace("', ",",").replace("['","").replace("\\n","\n").replace("'])","")

    fileItemW.write(formatString)
Run Code Online (Sandbox Code Playgroud)

GP8*_*P89 5

您的问题是您从文件的第一行读取并且不对其执行任何操作

lineString=fileItemR.readline()
Run Code Online (Sandbox Code Playgroud)

删除这个,你应该没问题

您还可以更简单地实现这一目标:

for lineString in fileItemR:
    lineList = lineString.split(",")
    lineList[0], lineList[1] = lineList[1], lineList[0]
    fileItemW.write(",".join(lineList[:99]))  #Don't use [:99] if there's only 100 items in the line, and this could change in the future. If you're discarding items past the 100th then this is fine.
Run Code Online (Sandbox Code Playgroud)