python错误地跳过列表中最后一个文件的最后一行
我用PythonV3.3编写了一个程序,它依次打开文件列表,并使用每个文件中的数据执行操作。但是,由于某些原因,程序在打开文件时始终忽略列表中最后一个文件的最后一行。以前的所有文件都可以正常读取。这些文件本身具有相同的格式,并且列表中最后一个文件中没有其他所有文件中不存在的额外空格或换行符 代码如下:python错误地跳过列表中最后一个文件的最后一行,python,Python,我用PythonV3.3编写了一个程序,它依次打开文件列表,并使用每个文件中的数据执行操作。但是,由于某些原因,程序在打开文件时始终忽略列表中最后一个文件的最后一行。以前的所有文件都可以正常读取。这些文件本身具有相同的格式,并且列表中最后一个文件中没有其他所有文件中不存在的额外空格或换行符 代码如下: counter3=0 for counter3 in range(counter3,numSteps): # open up each step in the list of steps acro
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']
脚本运行时是否正在写入文件 除了悬空的文件句柄和可能应该通过
f.close()
或f.flush()
清空的缓冲区之外,我没有看到代码中有任何错误
但是,您可以通过不使用list(filehandle)
而代之以for
循环来改进代码。正如你可能从评论中注意到的那样,这不是一种常见的做法
另外,由于替换指向filehandlecurrentStepFile
的变量,代码将不得不等待垃圾回收将其关闭
如果您在代码的其他地方也这样做,这很可能是将来出现此问题或其他问题的原因。numSteps defind在哪里?那里不应该有
currentStepFile.readlines()
?我只在文件句柄上看到一个列表……不,从技术上讲,这是可行的。@Fredrik不,list(filehandle)
导致隐式迭代/读取整个文件,就像对其执行for
一样。因此,我不得不尝试。即使我学到了新东西,我也不喜欢:-)嗨,乌诺德。澄清一下,“悬空文件句柄”是什么意思?您是否怀疑问题源于使用列表而不是循环,或者因为我没有关闭文件句柄,或者两者都关闭?@gwillymh悬空文件句柄是使用f=open(filename)
打开文件而不是使用f.close()
关闭文件的结果。由于Python会缓冲写入文件,以避免每次f.write()
操作时命中磁盘,因此当代码的其他部分尝试读取文件时,可能会出现文件不完整的情况。谢谢您取消代码。关闭所有打开的文件句柄似乎解决了这个问题。