Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my variable not defined and how do i fix this?

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?

like image 857
Megan Avatar asked Jan 01 '26 15:01

Megan


2 Answers

Because there will only defined, if this condition is true:

if W2 in line.split(",")[1]:

EDIT

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 = ''
like image 69
micharaze Avatar answered Jan 03 '26 03:01

micharaze


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.

like image 21
chepner Avatar answered Jan 03 '26 05:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!