Reputation: 1
""" I'm trying to convert a script to python 3 but I get this error
NameError: name 'prot_file' is not defined
yes I have used 2to3 but need some help in the way of the script use lines of a file to create a name a new one and then create that files
I want overcome the error
NameError: name 'prot_file' is not defined and know why is happening I cannot define the prot_file, surf_file and phi_file
fm = open(config_file_moved, 'w')
for line_full in file(config_file):
line = line_full.split()
if line[0]=='FILE':
if line[2]=='dielectric_interface':
prot_file = line[1]
prot_file_moved = prot_file + name
new_line = line[0] + '\t' + prot_file_moved + '\t' + line[2] + '\n'
fm.write(new_line)
if line[2]=='neumann_surface' or line[2]=='dirichlet_surface':
surf_file = line[1]
phi_file = line[3]
fm.write(line_full)
elif line[0]=='FIELD' and int(line[5])>0:
pqr_file_aux = line[7]
pqr_file = pqr_file_aux[:-4]
pqr_file_moved = pqr_file + name + '.pqr'
new_line = line[0] + '\t'
for i in range(1,len(line)):
if i==7:
new_line += pqr_file_moved + '\t'
else:
new_line += line[i] + '\t'
fm.write(new_line+'\n')
else:
fm.write(line_full)
fm.close()
print 'Protein file: ' + prot_file
print 'Sensor file: ' + surf_file
print 'Phi file: ' + phi_file + '\n'
Upvotes: -1
Views: 110
Reputation: 24691
You are currently defining prot_file
here:
for line_full in file(config_file):
line = line_full.split()
if line[0]=='FILE':
if line[2]=='dielectric_interface':
prot_file = line[1]
Now, in some languages, putting the declaration this many levels of indentation inwards would be a problem. Not so in python (2 or 3) - prot_file
will now be available outside the for
loop, and should be usable where you're using it, right?
...Unless you don't ever take that branch of if
statements. Because this is python, the prot_file
name only ever gets defined if that particular line is run. If you were to go the entire for
loop without the conditions line[0]=='FILE'
and line[2]=='dielectric_interference'
ever being true, then prot_file
would never be defined and inserted into the local namespace. In that case, trying to use prot_file
later (as you are in your print
statement) would yield the error you're seeing, because it was never actually defined.
The only real good solution to this is to just put a dummy definition (e.g. prot_file = ""
) at some point that the code will ALWAYS execute - such as the right before the for
loop.
It's also worth noting that you could have the same trouble with surf_file
and phi_file
for the same reason.
Upvotes: 1