2016-10-24 149 views
-4
def open_file(filename): 
    file_open= open(filename,"r") 
    return file_open 

当我尝试并调用我得到的结果如下功能:为什么这个功能不能打开我的文件?

>>> open_file(random.txt) 
Traceback (most recent call last): 
    File "<pyshell#17>", line 1, in <module> 
    open_file(random.txt) 
NameError: name 'random' is not defined 
+2

将参数作为字符串传递:'open_file('random.txt')' –

+3

如果您要编写字符串文字(例如文件名),则需要用引号括起来;例如'open_file('random.txt')' – khelwood

+0

所以当我调用函数时,文件名需要每次都在引号中? –

回答

2

尝试

open_file('random.txt') 

字符串在Python需要被引用。 random被解释为一个对象,并且是未定义的。

1

你忘了引号:

open_file('random.txt') 

蟒蛇认为是随机的对象,这显然你没有定义。引号使其成为一个字符串。

0

你只需要输入文件名作为字符串;这里是它必须怎么做:

>>> open_file('random.txt') 

注意,您的函数工作得很好,所有你需要做的是正确地调用它。

相关问题