打开和阅读文件

Ali*_*ias 1 python file-io python-2.7

from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,使用文本文件的名称作为参数'ex15_sample.txt',然后它返回文本文档中的内容.

但是,当我将最后一行更改为:

print txt
Run Code Online (Sandbox Code Playgroud)

然后它会显示:

<open file 'ex15_sample.txt', mode 'r' at 0x004A6230>
Run Code Online (Sandbox Code Playgroud)

我不确定区别是什么,因为txt变量应该打开文件.我知道该read命令读取文件,但在文档中,它说open一个文件对象返回,我不知道这意味着什么.

Pau*_* Bu 5

open()函数将返回一个表示确实的file对象:<open file 'ex15_sample.txt', mode 'r' at 0x004A6230>.

为了获得你需要的文件内容read().这就是为什么当你print txt.read()得到你所期望的.