文件操作
创建一个文件名字为filename
内容是
BJ
SH
GD
TW
打印文件编码
f = open("filename",‘r‘,encoding="utf-8")
print(f.encoding)
utf-8
打印在内存的编号
print(f.fileno())
3
1.文件读操作
1.1 open()方法,模式默认读
f = open("filename",encoding="utf-8")
data = f.read()
print(data)
BJ
SH
GD
TW
1.2 读前几行
f = open("filename",encoding="utf-8")
for i in range(2):
print(f.readline().strip())
BJ
SH
1.3 一行行读完
f = open("filename",encoding="utf-8")
for i in f:
print(i.strip())
BJ
SH
GD
TW
1.4 高效读到第x行
count = 0
f = open("filename",encoding="utf-8")
for i in f:
if count == 3:
print(‘----------------‘)
count += 1
print(i.strip())
count += 1
BJ
SH
GD
----------------
TW
ssssss
2.文件写操作
2.1 w写模式,如果没有此文件就创建
f = open("filename2",‘w‘,encoding="utf-8")
f.write("wwwww")
f.close()
f1 = open("filename2",encoding="utf-8")
data = f1.read()
print(data)
f.close()
wwwww
2.2 a追加模式
在文件尾部追加
f = open("filename",‘a‘,encoding="utf-8")
f.write("\nssssss")
f.close()
BJ
SH
GD
TW
ssssss
2.3读+追加模式
f = open("filename","r+",encoding="utf-8")
f.write("\n------haha------------")
for i in f:
print(i.strip())
2.4 文件修改
f = open("filename","r",encoding="utf-8")
f1 = open("filename1","w",encoding="utf-8")
for line in f:
if "h" in line:
line = line.replace(‘h‘,‘g‘)
f1.write(line)
f.close()
f1.close()
3.指针操作
f = open("filename",encoding="utf-8")
print(f.tell()) #查看当前指针位置
print(f.readline())
print(f.tell())
f.seek(0) #指针回到0
print(f.tell())
print(f.readline())
print(f.tell())
0
BJ
4
0
BJ
4
4.判断文件是否可读可移可写
f = open("filename",‘r‘,encoding="utf-8")
print(f.readable())
print(f.seekable())
print(f.writable())
True
True
False
5.flush方法和buffer方法
f = open("filename",‘r‘,encoding="utf-8")
print(f.flush())#从内存写入磁盘
print(f.buffer)
None
<_io.BufferedReader name=‘filename‘>
6.实现进度条
import sys,time
for i in range(10):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.5)
##########
7.截断
f = open("filename","a",encoding="utf-8")
f.seek(0) #指定指针到0的位置
f.write("123456")
f.truncate(2) #截断2字符
filename文件中 只保留2个字符
BJ
原文地址:https://www.cnblogs.com/wsy1030/p/9013068.html