2017-02-25 54 views
-2

使用头文件第一本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

我在做有关语法错误的东西,或者也许我没有得到如何打印模块的作品?这本书没有给我任何线索。我在这里和其他一些论坛也检查了很多问题,但是我的代码没有任何问题,实际上我倾斜了。

+0

'OUT =打开( “man_speech.txt”, “W”); out = open(“other_speech.txt”,“w”)' - 再次阅读该教程。 – TigerhawkT3

+0

什么?另外,为什么重复?我花了50分钟寻找类似的问题,但我没有找到任何 – Monok

+0

您需要查看变量名称是如何工作的。重复内容说明如何使用文件。 – TigerhawkT3

回答

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 

你没有的open结果分配给man_speechout。因此,错误消息:

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

当您打开此文件:

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

您指定的文件到out变量,有没有这样的名为man_speech的变量。这就是为什么它会产生NameError并且说man_speech没有被定义。

您需要将其更改为

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

同为other_speech

+0

哦... ahahahah,好的,我明白了!所以,无论何时我需要将数据保存到文件中,我需要创建一个与我的文件完全一样的变量。 – Monok

+0

不可以。您可以将它们称为file1和file2,但您需要使用file1和file2来引用它们。 'file1 = open(“man_speech.txt”,“w”)''print(man,file = file1)''file1.close()' –

+0

只要有意义,你和你的同事,你使用相同的变量名来引用它:) –