對於下面的工作代碼,我訴諸創建一個類實例來存儲我的文件輸出[a_string]的名稱變量和文件對象本身[f_object]。我發現在第一個if語句中分配的變量沒有出現在以下elif語句內的作用域中。變量賦值在裏面,然後如果循環
#Text file splitter, data bewteen the '*' lines are copied into new files.
class Output_file():
def __init__(self,a_string='none',f_object='none'):
self.name=a_string
self.foutput=f_object
outputfile=Output_file()
n=0
filehandle=open('original file.txt')
for line in filehandle:
if line[0]=='*': #find the '*' that splits the rows of data
n+=1
outputfile.name = 'original file_'+str(n)+'.txt'
outputfile.foutput= open(outputfile.name,'w')
outputfile.foutput.write(line)
elif len(line.split()) ==5 and n > 0: #make sure the bulk data occurs in blocks of 5
outputfile.foutput= open(outputfile.name,'a+')
outputfile.foutput.write(line)
outputfile.foutput.close()
我是否必須使用類實例來存儲文件名和對象,還是有更好的方法嗎?
你怎麼知道他們不會攜帶到,如果我想模仿你的風格,我想這樣的代碼它接下來的elif聲明? – 2012-02-29 18:40:12