#!/usr/bin/python
with open('works.txt', 'r') as f:
data1 = f.read(22)
print(data1)
f.seek(0, 0)
data2 = f.read(22)
print(data2)
在示例中,我们从文本流中读取了22个字符。然后我们将流位置设置回开头并再次读取22个字符。
$ ./seeking.py
Lost Illusions
Beatrix
Lost Illusions
Beatrix
告诉函数
tell函数返回当前流位置。
#!/usr/bin/python
with open('works.txt', 'r') as f:
print(f'The current file position is {f.tell()}')
f.read(22)
print(f'The current file position is {f.tell()}')
f.seek(0, 0)
print(f'The current file position is {f.tell()}')
我们使用read和seek移动流位置,并使用tell打印它。
$ ./telling.py
The current file position is 0
The current file position is 22
The current file position is 0
Python使用try/except/finally读取文件
with语句简化了我们读取文件时的工作。如果没有with,我们需要手动处理异常并关闭资源。
#!/usr/bin/python
f = None
try:
f = open('works.txt', 'r')
for line in f:
print(line.rstrip())
except IOError as e:
print(e)
finally:
if f:
f.close()
在示例中,我们使用try、except和finally关键字处理异常和资源释放。
Python读取二进制文件
在下面的例子中,我们读取了一个二进制文件。
#!/usr/bin/python
with open('web.png', 'rb') as f:
hexdata = f.read().hex()
n = 2
data = [hexdata[i:i+n] for i in range(0, len(hexdata), n)]
i = 0
for e in data:
print(e, end=' ')
i += 1
if i % 20 == 0:
print()
print()
该示例读取PNG文件。它将数据输出为十六进制值。
with open('web.png', 'rb') as f:
我们以读取和二进制模式打开PNG文件。
hexdata = f.read().hex()
我们读取所有数据并使用hex函数将其转换为十六进制值。
n = 2
data = [hexdata[i:i+n] for i in range(0, len(hexdata), n)]
我们将字符串分成两个字符的列表。
i = 0
for e in data:
print(e, end=' ')
i += 1
if i % 20 == 0:
print()