打开和关闭文件
文件打开后,如果读写操作完成,必须关闭文件。
f = open('test.txt', 'w')
f.close()
文件的操作模式:
- r:只读
- w:覆盖写入
- a:追加写入
- b:以二进制模式
- a+:读写,文件指针在末尾,只能追加
- w+:读写,打开文件时先清除内容
- r+:读写,文件指针在末尾
with语句
可以不用担心忘记写close()
的问题
with open('test.txt', 'w') as f:
pass
常用的几个方法或者模块
read(n)
- 当
n
的值不给时,读取文件所有的内容; n
表示从文件读取n个字符
with open('test.txt', 'r') as f:
data = f.read(10)
print(data)
readline()
每次读取一行,文件指针自动指向下一行开始位置。
with open('test.txt', 'r') as f:
line = f.readline()
while line:
print(line)
line = f.readline()
readlines()
读取文件所有行,并返回一个list,每一行为一个list的member。
with open('test.txt', 'r') as f:
data = f.readlines()
print(data)
使用这个方法可以遍历文件,但是对于大文件比较占用内存,可以使用readline()
函数配合while
语句进行逐行遍历。也可以使用下述方法:
with open('test.txt', 'r') as f:
# 使用for语句将f转换成可迭代的对象
for line in f:
print(line)
write()
向文件写入字符串。
with open('test.txt', 'a') as f:
f.write('hahah')
writelines()
向文件写入字符串或者列表。
with open('test.txt', 'a') as f:
l = ['I','LOVE','U']
f.writelines(l)
seek(offset,from)
改变指针的位置,offset
表示指针偏移的量,from
表示从哪里开始偏移。
from值的范围:
with open('test.txt', 'r') as f:
f.seek(4,0)
data = f.read()
print(data)
tell()
返回文件指针当前所在的位置。
with open('test.txt', 'r') as f:
f.seek(4,0)
print(f.tell())
pickle模块
一种持久化数据保存方式。
用于将python对象进行序列化和反序列化,保存形式为二进制文件,所以打开文件的模式为rb
、wb
、ab
等。
与JSON模块类似,但是json处理的是unicode文本。
使用到的两个函数:
import pickle
# 序列化任何对象到文件
with open('test.txt', 'wb') as f:
list = ['cy','love','why']
pickle.dump(list,f)
# 从文件反序列化
with open('test.txt', 'rb') as f:
list = ['cy','love','why']
print(pickle.load(f))
shelve模块
另一种对象持久化保存方法,将对象保存到文件里面,缺省(即默认)的数据存储文件是二进制的,可以作为一个简单的数据存储方案。
通常保存键值数据。
import shelve
with shelve.open('test1.txt') as db:
db['name'] = 'cy'
db['love'] = {'girlfrend':'why'}
print(db['love'])