持久化存储的过程
文件的打开和关闭和读写操作
1.打开文件
"""
mode 模式
r 只读模式
w 只能写入(清空文件内容)
a+ 读写(追加文件内容)
"""
f = open('doc/hello.txt', mode='r') #相对路径
## 2. 文件的读写操作
print(f.read())
# print(f.write('java\n'))
## 3.关闭文件
f.close()
open 对应的模式
源代码
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode.
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
解释
r 是默认模式,默认情况下只读
w 表示写入模式(只能写入),会清空文件内容
x 表示创建一个新的文件并且进入写入模式
a 表示进入写入模式,如果文件存在,写入的内容会追加在文件的最后面(不会清空内容)
b 二级制模式
t 文本模式
+ 进入读写模式,在磁盘中打开该文件
u 换行模式(反对) ## 没有用过
注:文件使用完毕之后,一定要关闭文件,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的
with语句(自动关闭文件)
会自动的关闭文件
"""
with语句
"""
with open('doc/test.txt', 'w+') as f:
f.write('hello world\n') # 写入文件
f.seek(0, 0) # 移动指针到最开始
print("当前指针的位置:", f.tell())
f.seek(0, 2)
print("当前指针的位置:", f.tell())
# seek(offset,from)参数: offset:偏移量 from:方向
#0:表示文件开头 1:表示当前位置 2:表示文件末尾
print(f.read()) # 读取文件内容(从当前位置开始读取)