打开一个已存在的文件或创建一个新的文件
open(name,mode)
name 为目标文件名或者具体路径
mode 为打开文件的访问模式:只读,写入,追加等 即 r,w,a等
例如
file=open('text.txt','w')
file为open函数的文件对象
1.写入 write()
file=open('text.txt','w')
file.write('你想写入的东西')
file.close()
w模式覆盖文件内容
a模式在文件末尾追加
2.读 read()
readlines 和 readline
前者一次性读取文件内容 返回一个列表 每一行的数据为一个元素
file=open('text.txt')
content=file.readlines()
print(content)
file.close()
后者一次读取一行内容
file=open('text.txt')
content=file.readline()
print(content) # 第一行内容
content=file.readline()
print(content) # 第二行内容
file.close()
3.seek() 用来移动文件指针
r:指针位于文件的开头
a:指针位于文件的结尾
file=open('text.txt')
file.seek(偏移量,起始位置)
file.close()
起始位置:
0:文件开头
1:当前位置
2:文件结尾