-2

在 2010 年编写 Head First Python 书籍时,我遇到了一个练习,我必须将一个列表打印到特定文件中,然后将另一个列表打印到另一个文件中。做了所有的代码,一切正常,除了打印模块说文件名没有定义,这很奇怪,因为练习的解决方案是我的完全相同的代码。

import os

man = []
other = []

try: 

    data = open('ketchup.txt')

    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(":", 1)
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print("The data file is missing!")
print(man)
print(other)

try:
    out = open("man_speech.txt", "w")
    out = open("other_speech.txt", "w")
    print(man, file=man_speech)          #HERE COMES THE ERROR
    print(other, file=other_speech)

    man_speech.close()
    other_speech.close()
except IOError:
    print("File error")

这是来自 IDLE 的错误:

回溯(最后一次调用):文件“C:\Users\Monok\Desktop\HeadFirstPython\chapter3\sketch2.py”,第 34 行,在 print(man, file=man_speech) NameError: name 'man_speech' is not defined

我是在语法上做错了什么,还是我不明白打印模块的工作原理?这本书没有给我任何线索。我还在这里和其他一些论坛中检查了很多问题,但我的代码似乎没有任何问题,而且我实际上是倾斜的。

4

2 回答 2

2

当您在此处打开文件时:

out = open("man_speech.txt", "w")

您正在将文件分配给out变量,没有名为man_speech. 这就是为什么它提出 aNameError并说man_speech未定义。

您需要将其更改为

man_speech = open("man_speech.txt", "w")

同样对于other_speech

于 2017-02-25T01:01:14.467 回答
1

文件名似乎有问题:

out = open("man_speech.txt", "w")    # Defining out instead of man_speech
out = open("other_speech.txt", "w")  # Redefining out
print(man, file=man_speech)          # Using undefined man_speech
print(other, file=other_speech)      # Using undefined other_speech

您没有将结果分配给opentoman_speech而是分配给out。因此出现错误消息:

NameError: name 'man_speech' is not defined

代码应该是

man_speech = open("man_speech.txt", "w")
other_speech = open("other_speech.txt", "w")
print(man, file=man_speech)
print(other, file=other_speech)
于 2017-02-25T00:56:42.443 回答