2013-03-04 95 views
1

我在Python v3.3中編寫了一個程序,依次打開一個文件列表並使用每個文件中的數據執行操作。但是,由於某些原因,程序在打開文件時始終忽略列表中最後一個文件的最後一行。所有以前的文件都正常讀取。這些文件本身具有相同的格式,列表中最後一個文件中沒有其他空白或換行符不在所有其他文件中。python錯誤地跳過列表中最後一個文件的最後一行

的代碼如下:

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'] 
+1

其中是numSteps defiend? – Hoopdady 2013-03-04 20:44:32

+0

不應該有'currentStepFile.readlines()'在那裏?我只看到一個文件句柄的列表... – 2013-03-04 20:44:42

+0

不,從技術上講,這將工作。 – Hoopdady 2013-03-04 20:49:45

回答

0

是腳本運行時被寫入的文件嗎?

除了懸掛文件句柄,或許應該通過f.close()f.flush()清空緩衝區,我沒有看到代碼中的任何錯誤。

但是,您可以通過不使用list(filehandle)來改進代碼,而是用for循環替換它。正如您可能注意到的評論,這不是一個常見的做法。

此外,因爲您替換指向文件句柄currentStepFile的變量,您的代碼將不得不等待垃圾回收才能關閉它。

如果您也在代碼中的其他位置執行此操作,則可能是未來出現此問題或其他問題的原因。

+0

Hi Unode。澄清,w你的意思是'搖晃文件句柄'的帽子?你懷疑問題是由於使用列表而不是循環,還是因爲我沒有關閉文件句柄,或者兩者兼而有之? – gwilymh 2013-03-04 21:37:53

+0

@gwilymh一個懸而未決的文件句柄是用'f = open(filename)'打開一個文件的結果,而不是用'f.close()'關閉它。由於Python會緩衝寫入文件以避免在每個'f.write()'操作時觸及磁盤,所以當您的其他代碼部分嘗試讀取文件時,可能會發生文件不完整。 – Unode 2013-03-05 11:54:54

+0

謝謝你Unode。關閉所有打開的文件句柄似乎已經解決了這個問題。 – gwilymh 2013-03-06 17:05:22

相關問題