Python打印模块说文件名未定义

2024-03-28 15:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在写一本2010年的头版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")

以下是来自空闲的错误:

Traceback (most recent call last): File "C:\Users\Monok\Desktop\HeadFirstPython\chapter3\sketch2.py", line 34, in print(man, file=man_speech) NameError: name 'man_speech' is not defined

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


Tags: 文件代码txtdatalineopenspeechrole
2条回答

在此处打开文件时:

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

您正在将文件分配给out变量,不存在名为man_speech的此类变量。这就是为什么它会引发一个NameError,并说man_speech没有定义。

你得把它改成

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

同样适用于other_speech

文件名似乎有问题:

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

您不会将open的结果赋给man_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)

相关问题 更多 >