Python print module says the file name is not defined
本问题已经有最佳答案,请猛点这里访问。
在2010年的头一本Python书籍上,我遇到了一个练习,我必须将一个列表打印到一个特定的文件中,将另一个列表打印到另一个文件中。所有的代码,除了打印模块没有定义文件名之外,一切都正常,这很奇怪,因为练习的解决方案和我的代码完全相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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
我是否在语法方面做了一些错误的事情,或者可能我不知道打印模块是如何工作的?这本书没有给我任何线索。我在这里和其他一些论坛上也检查了很多问题,但是我的代码似乎没有问题,实际上我有点倾斜。
在此处打开文件时:
1 | out = open("man_speech.txt","w") |
您正在将文件分配给
你需要把它改成
1 | man_speech = open("man_speech.txt","w") |
同适用于
文件名似乎有问题:
1 2 3 4 | 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 |
您不将EDOCX1的结果(0)分配给
1 | NameError: name 'man_speech' is not defined |
代码应该是
1 2 3 4 | man_speech = open("man_speech.txt","w") other_speech = open("other_speech.txt","w") print(man, file=man_speech) print(other, file=other_speech) |