我正在嘗試編寫一個基於字典值打開文件的腳本。對於每個鍵/值,它會根據該值的名稱打開一個文件,並將該文件分配給值的名稱(我認爲這裏出錯了)。到目前爲止,它以正確的名稱爲我打開這些文件,因此可行。然而,我認爲我分配open(file)函數的名稱是錯誤的,因爲我的函數的其餘部分不再打開這些文件,並且我無法關閉它們。我的腳本 例子:Python賦值函數字典值
filelist=[]
codeconv={"agt":"r1p1d", "aga":"r2p1d"}
for value in codeconv.values():
value=open("c:\Biochemistry\Pythonscripts\Splittest\split"+value+".txt", 'w')
filelist.append(value)
"Here I do something with the files"
for f in filelist:
f.close()
所以問題是,我該如何分配打開(文件)功能,以正確的名稱? (例如,這裏是r1p1d和r2p1d)我以後如何再次調用它們?
我現在得到的錯誤是: AttributeError:'str'object在f.close()行上沒有屬性'close' 。
編輯:現在的工作,因爲我想它,使用下面的代碼:(我還包括「我在這裏做一些事情」的一部分,現在只是爲了清楚起見)
result=open("C:\\Biochemistry\\Pythonscripts\\Illuminaresults.txt", "r")
filelist=[]
codeconv={"agt":"r1p1d", "aga":"r2p1d"}
opened_files={}
for key, value in codeconv.items():
filename="c:\Biochemistry\Pythonscripts\Splittest\split"+value+".txt"
file=open(filename, 'w')
opened_files.update({key: file})
for line in result:
if line[0]==">":
lastline=line
if line[0:3] in codeconv and len(line)==64:
f=opened_files[line[0:3]]
f.write(lastline+line)
else: continue
for f in opened_files.values():
f.close()
result.close()
我有另外一個問題,雖然現在當我嘗試編寫腳本的下一部分時,但這可能是另一個問題的原因,因爲它提供了與此部分無關的Windowserror。感謝所有的幫助!
`filelist`聲明在哪裏? – 2010-12-22 10:04:38
filelist在此之前聲明,我的腳本中只有filelist = [] – Max 2010-12-22 10:06:39
不要使用`file`作爲變量。它會隱藏內置類型。 – 2010-12-22 18:07:13