程序保持返回无,即使我没有定义

Dan*_*nny 2 python attributes mode

我正在研究http://learnpythonthehardway.com的额外问题.编写打开并读取文件的程序后,我尝试更改它以向open命令添加模式.但每当我这样做时,它返回None以及文件内容.

这是代码:

from sys import argv

script, filename = argv

txt = open(filename, "r")

print "Here's your file %r:" % filename
print txt.read()
print txt.close()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again, "r")

print txt_again.read() 
print txt_again.close()
Run Code Online (Sandbox Code Playgroud)

这是打印出来的:

$ python ex15.py filey.txt
Here's your file 'filey.txt':
whatever
None
Type the filename again:
> filey.txt
whatever
None
Run Code Online (Sandbox Code Playgroud)

线条之间有斜线.

我发现了一个问题,解释说当你没有指定时,python会None自动返回.但是,当我尝试使用return命令时,或者除了print之外,它还需要一个定义.当我添加一个定义时,我无法使其余的代码工作.我怎么能摆脱这个None

我也很感激,如果有人能解释为什么它出现在"r"模式,但不是没有它.

Ble*_*der 6

每个函数都在Python中返回一个值.你打印出的结果txt.close()恰好是None:

print txt.close()
Run Code Online (Sandbox Code Playgroud)

只需删除该print声明,您应该没问题:

txt.close()
Run Code Online (Sandbox Code Playgroud)