文件常用操作
结构体
1. open(文件路径, 编码, 动作)
注:进行文件操作后,需及时释放,使用close()
2. with open(文件路径, 编码, 动作) as f1:
pass
注:自动释放
动作:
1. r
2. rb
3. r+
4. w
5. wb
6. w+
7. a
8. ab
9. a+
文件读取方法
1. read()
f1 = open("test.txt", encoding="utf-8", mode="r")
f1.read()
f1.close()
2. readline()
f1 = open("test.txt", encoding="utf-8", mode="r")
f1.readline()
f1.readline()
f1.close()
3. readlines()
f1 = open("test.txt", encoding="utf-8", mode="r")
f1.readlines()
f1.close()
4. read(n)
f1 = open("test.txt", encoding="utf-8", mode="r")
f1.read(3)
f1.close()
5. for循环读取,推荐使用
f1 = open("test.txt", encoding="utf-8", mode="r")
for i in f1:
print(i)
f1.close()
文件写入方法
1. write()
f1 = open("test.txt", encoding="utf-8", mode="w")
f1.write("ABC")
f1.close()
文件的其他操作方法
1. seek()
2. tell()
3. readable()
4. writeable()
5. flush()
6. next()
文件改逻辑: