在python中打开变量文件

时间:2013-12-12 22:43:31

标签: python python-2.7

我正在尝试创建一个涉及用户在python中打开文件的程序。以下是相关代码:

def fileopen():
    source = input("Enter the name of the source file (w/ extension): ")
    f = open("%s" %source, "r") #open the file
    filelist = f.read()
    f.close()
    print(filelist)
    encrypt(filelist)

这导致以下错误:

Enter the name of the source file (w/ extension): source

Traceback (most recent call last):
  File "C:\Python27\Encrypt\Encrypt.py", line 27, in <module>
    fileopen()
  File "C:\Python27\Encrypt\Encrypt.py", line 2, in fileopen
    source = input("Enter the name of the source file (w/ extension): ")
  File "<string>", line 1, in <module>
NameError: name 'source' is not defined
>>> 

当我将它设置为静态文件(例如source.txt)时,它正在工作,但我需要能够选择要使用的文件。

1 个答案:

答案 0 :(得分:4)

不要使用input();在这里使用raw_input()

source = raw_input("Enter the name of the source file (w/ extension): ")
f = open(source, "r")

input() 将输入计算为作为Python表达式。如果您在提示符下键入source,Python会尝试将其视为变量名称。

>>> input('Gimme: ')
Gimme: source
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'source' is not defined
>>> input('Gimme: ')
Gimme: Hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Hello' is not defined

raw_input()只给你一个字符串,没有别的。