Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
文件和目录
229
读取到文件结尾。
>>> bdata = fin.read()
>>> len(bdata)
1
>>> bdata[0]
255
在调用
seek()
函数时不需要额外调用
tell()
。我只是想说明两个函数返回
的偏移值是相同的。
下面的例子是从文件当前位置开始查找的:
>>> fin = open('bfile', 'rb')
接下来的例子定位到了文件倒数第
2
字节:
>>> fin.seek(254, 0)
254
>>> fin.tell()
254
向前移动一字节:
>>> fin.seek(1, 1)
255
>>> fin.tell()
255
最后,读取至文件末尾:
>>> bdata = fin.read()
>>> len(bdata)
1
>>> bdata[0]
255
这些函数主要用于二进制文件。你也可以将其用于文本文件,但除非该文件采用的是
ASCII
编码
(一个字符对应一字节),否则计算偏移值很麻烦。具体取决于文本编码,最流
行的
UTF-8
编码对每个字符使用的字节数不尽相同。
14.2
内存映射
读写文件的另一种方法是使用
mmap
模块进行
内存映射
。这使得文件内容看起来就像是内存
中的
bytearray
14.3
文件操作
和很多其他语言一样,
Python
也模仿了
Unix
的文件操作。有些函数(比如
chown()
230
14
chmod()
)采用了相同的名称,还有一些是
Python
独有的。
首先,我将展示
Python
如何使用
os.path
模块以及更新的
pathlib ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223