with open("RoundOneTotalScores.txt") as f:
lines = f.readlines()
values = [int(line.split(',')[1]) for line in lines]
smallest = (min(values))
smallest2 = (sorted(values)[:2])
highest4 = (sorted(values)[2:])
W1 = str(highest4[0])
W2 = str(highest4[1])
W3 = str(highest4[2])
W4 = str(highest4[3])
Myfile = open("RoundOneTotalScores.txt", "r")
for line in Myfile:
if W1 in line.split(",")[1]:
W1L = (line.split(",")[0])
for line in Myfile:
if W2 in line.split(",")[1]:
W2L = (line.split(",")[0])
for line in Myfile:
if W3 in line.split(",")[1]:
W3L = (line.split(",")[0])
for line in Myfile:
if W4 in line.split(",")[1]:
W4L = (line.split(",")[0])
Myfile = open("RoundOneWinners.txt", "a")
Myfile.write(W1L)
Myfile.write(",")
Myfile.write(W1)
Myfile.write("\n")
Myfile.write(W2L)
Myfile.write(",")
Myfile.write(W2)
Myfile.write("\n")
Myfile.write(W3L)
Myfile.write(",")
Myfile.write(W3)
Myfile.write("\n")
Myfile.write(W4L)
Myfile.write(",")
Myfile.write(W4)
Myfile.close()
The code above does the following: opens a text file which contains six letters, each with a number. It finds the four highest of those numbers and then finds the equivalent letters. When I try to save it to a new text file, this error comes up:
Traceback (most recent call last):
File "D:\NEA Real\Test5.py", line 37, in <module>
Myfile.write(W2L)
NameError: name 'W2L' is not defined
Why is W2L not defined and how do I define it?
Because there will only defined, if this condition is true:
if W2 in line.split(",")[1]:
Added solutions from the commend of roganjosh and me.
Define all W1L - W4L on the top with an empty string.
W1L = ''
W2L = ''
W3L = ''
W4L = ''
or in else:
for line in Myfile:
if W2 in line.split(",")[1]:
W2L = (line.split(",")[0])
else:
W2L = ''
You can't iterate over the file multiple times like this; after the first loop completes, you have reached the end of the file, and the next three loops never do anything; there is no more data to read.
Instead, combine your loops into one:
for line in Myfile:
value, field = line.split(",")[0:2]
if W1 in field:
W1L = value
if W2 in field:
W2L = value
if W3 in field:
W3L = value
if W4 in field:
W4L = value
There is still the risk that any particular variable does not get set, if the corresponding tag is not found. There is also a chance that you find the same tag multiple times, in which case you will only record the last one found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With