随机存取

简介

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#coding:utf-8

import os

f = open(r'./somefile.txt','w')
f.write('01234567890123456789')

f.seek(5)
f.write('Hello World!')

f.close()

f = open(r'./somefile.txt','r')
a = f.read()
print(a)

f.close()

f = open(r'./somefile.txt')
b = f.read(3)
print(b)
c = f.read(2)
print(c)
print(f.tell()) # 反映f在文件的第多少个位置。

# 可以用with结构来省去 close的使用

with open('somefile.txt') as somefile:
print(somefile.read())
# *********** 不用close