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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

可编程网络自动化

可编程网络自动化

Jason Edelman, Scott S. Lowe, Matt Oswalt
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
量子计算机编程:从入门到实践

量子计算机编程:从入门到实践

Eric R. Johnston, Nicholas Harrigan, Mercedes Gimeno-Segovia
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787115586223