python错误地跳过lis中最后一个文件的最后一行

2024-04-18 22:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pythonv3.3中编写了一个程序,它依次打开一个文件列表,并使用每个文件中的数据执行一个操作。但是,由于某些原因,程序在打开文件时始终忽略列表中最后一个文件的最后一行。以前的所有文件都正常读取。文件本身具有相同的格式,并且列表中最后一个文件中没有其他所有文件中不存在的额外空格或换行符。你知道吗

代码如下:

counter3=0
for counter3 in range(counter3,numSteps):
# open up each step in the list of steps across the chromosomal segment:
    L=shlex.shlex(stepFileIndex[counter3],posix=True)
    L.whitespace += '\t'
    L.whitespace_split = True
    L=list(L)
    #print(L)
    stepNumber = int(L[0])
    stepStart = int(L[1])
    stepStop = int(L[2])
    stepSize = int(stepStop-(stepStart-1))
#Now open the file of SNPs corresponding with the window in question and convert it into a list:
    currentStepFile = open(("C:/Users/gwilymh/Desktop/Python/Sliding Window Analyses-2/%s_%s_step_%s.txt")%(str(segmentNumber),str(segmentName),str(counter3+1)),'r')
    currentStepFile = list(currentStepFile)
    nSNPsInCurrentStepFile = len(currentStepFile)
    print("number of SNPs in this step is:", nSNPsInCurrentStepFile)
    print(currentStepFile)

列表中的最后两个文件如下:

1_segment1_step_7.txt
['1503', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'C']
['1505', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'G']

1_segment1_step_8.txt
['1950', 'G', 'G', 'G', 'C', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G']
['1967', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'G']

Tags: 文件ofthein程序txt列表step
1条回答
网友
1楼 · 发布于 2024-04-18 22:14:24

脚本运行时是否正在写入文件?你知道吗

除了挂起的文件句柄和可能应该通过f.close()f.flush()清空的缓冲区之外,我在代码中没有看到任何错误。你知道吗

但是,您可以通过不使用list(filehandle)而改为使用for循环来改进代码。正如你可能注意到的评论,这不是一种常见的方式。你知道吗

另外,因为替换了指向filehandlecurrentStepFile的变量,所以代码必须等待垃圾回收关闭它。你知道吗

如果您在代码中的其他地方也这样做,这很可能是将来出现此问题或其他问题的原因。你知道吗

相关问题 更多 >