为什么我的变量没有定义,我该如何解决?

时间:2017-09-16 12:39:50

标签: python list text-files

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()

上面的代码执行以下操作:打开一个包含六个字母的文本文件,每个字母都带有一个数字。它找到这些数字中的四个最高,然后找到相应的字母。当我尝试将其保存到新的文本文件时,会出现此错误:

Traceback (most recent call last):
File "D:\NEA Real\Test5.py", line 37, in <module>
Myfile.write(W2L)
NameError: name 'W2L' is not defined

为什么没有定义W2L以及如何定义它?

4 个答案:

答案 0 :(得分:5)

因为只会定义,如果这个条件是true

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

修改

添加了roganjoshme推荐的解决方案。

使用空字符串在顶部定义所有W1L - W4L

W1L = ''
W2L = ''
W3L = ''
W4L = ''

或其他地方:

for line in Myfile:
    if W2 in line.split(",")[1]:
        W2L = (line.split(",")[0])
    else:
        W2L = ''

答案 1 :(得分:2)

你不能像这样多次迭代文件;在第一个循环完成后,您已到达文件的末尾,接下来的三个循环从不执行任何操作;没有更多的数据可供阅读。

相反,将您的循环组合成 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

如果找不到相应的标签,仍然存在未设置任何特定变量的风险。您也有可能多次找到相同的标签,在这种情况下,您只会记录最后找到的标签。

答案 2 :(得分:2)

当您读取整个文件时,读取光标到达文件末尾。如果您想再次阅读,则需要使用seek(0)将其设置为开头。

Myfile = open("RoundOneTotalScores.txt", "r")

for line in Myfile:
    if W1 in line.split(",")[1]:
        W1L = (line.split(",")[0])

Myfile.seek(0)

for line in Myfile:
    if W2 in line.split(",")[1]:
        W2L = (line.split(",")[0])

答案 3 :(得分:1)

尝试使用字典,避免使用变量,因此如果文件中的任何行丢失,则不会引发NameError。以下是一些示例,您如何编写代码:

scores = {}

with open("RoundOneTotalScores.txt") as f:
    lines = f.readlines()
    for line in lines:
        user, score = line.split(',')
        user = user.strip()
        scores[user.strip()] = int(score)

winners_scores = sorted(scores.values())[2:]

winners = {k: v for k, v in scores.items() if v in winners_scores}

with open("RoundOneWinners.txt", "a") as f:
    for winner_and_score in winners.items():
        f.write(','.join(winner_and_score))