文件

未匹配的标注

文件对象是Python代码连接电脑上外部文件的主要接口。它们能被用来读写文本备忘录,音频片段,Excel文档,保存的电子邮件信息和电脑上碰巧保存下来的任何东东。文件是一个核心类型,但它们有些奇怪——没有创建它们的专用文字语法。确切的说,要创建一个文件对象,可以调用内置 Open 函数,传入一个外部文件名和一个可选的处理模式的字符串。

比如,要创建一个文本输出文件,要传入它的名称和 'w' 处理模式字符串来写数据:

>>> f = open('data.txt', 'w') # 在输出模式创建一个新文件 ('w' 是写)
>>> f.write('Hello\n') # 向文件写字符串
6
>>> f.write('world\n') # 在Python 3.X中返回写入项的数量
6
>>> f.close() # 关闭文件将缓存区数据写入磁盘

这在当前目录创建了一个文件并写入文本(如果需要在电脑上的任何地方访问它,这个文件名可以是一个完整目录路径)。要读回刚写入的数据,在 r 处理模式(用于读取文本输入)重新打开文件——如果在调用中省略模式,这是默认模式。然后将文件内容读入字符串并展示它。文件内容在脚本中总是字符串,不管文件包含的数据类型:

>>> f = open('data.txt') # 'r' (read) 是默认的处理模式
>>> text = f.read() # 将整个文件读入字符串
>>> text
'Hello\nworld\n'
>>> print(text) # print 解释控制字符
Hello
world
>>> text.split() # 文件内容总是字符串
['Hello', 'world']

其他文件对象的方法支持额外特性,这里没有时间来讨论了。比如,文件对象提供了更多读写的方法,还有其他工具。然而,随后将看到:当今读取文件的最佳方式根本不是读取它——文件提供了一个迭代器,它自动在 for 循环和其他上下文中逐行读取:

>>> for line in open('data.txt'): print(line)

本书后面将看到全套的文件方法,但如果现在要快速浏览,可以对任何打开的文件运行一个 dir 调用,并对随后出现的方法名称中的任何一个使用 help 调用:

>>> dir(f)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']

>>> help(f.seek)
Help on built-in function seek:

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
    Change stream position.

    Change the stream position to the given byte offset. The offset is
    interpreted relative to the position indicated by whence.  Values
    for whence are:

    * 0 -- start of stream (the default); offset should be zero or positive
    * 1 -- current stream position; offset may be negative
    * 2 -- end of stream; offset is usually negative

    Return the new absolute position.

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~