For the following working code, I resorted to creating a class instance to store the name variable of my file output [a_string] and the file object itself [f_object]. I found that variables assigned inside the first if statement did not appear in the scope inside the following elif statement.
#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()
Do I have to use a class instance to store the file name and object or is there a better way?
Variables defined in either
iforelifstatement should appear in the other. For example:This would not be the case in block-scoped languages, but unfortunately python is not block-scoped, and thus this should work.
Do note however that for this to work, your
name=must execute before you attempt to use it. That is, yourifstatement MUST execute at least once before yourelifstatement.Your code lacks comments, but I assume your data looks somewhat like:
And you want to split them into separate files, but only if it’s “valid” data. I’d code it like so if I wanted to imitate your style:
I’d however personally prefer to write it like so: