第四章 文件操作&拷贝
4.1文件操作
4.1.1 创建文件
1:
f1 =open('a.txt',mode='w',encoding='utf-8')
2:
with open('a.txt',mode='w',encoding='utf-8') as f1 :
# 自动缩进 编写文件 自己关闭文件
4.1.2打开模式
- w 写 会清空原来文件内容
- r 读 read
- a 追加 写到文件最后
- w+ / r+ / a+ 读写操作
- wb / rb / ab 用的是二进制操作 断点续传
- w+b / r+b / a+b
4.1.3关闭文件
f1 =open('a.txt',mode='w',encoding='utf-8')
f1.close() # 每个文件打开操作后 关闭
4.1.4读/写/追加
w 写入文件
# -------------------写,但覆盖原来文件------------------- f = open('文件',mode='w',encoding=('utf-8')) f.write('吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮') f.close()
r 读取文件内容
# --------------读 r------------------------------------ f = open('文件',mode='r',encoding=('utf-8')) s=f.read() print(s) f.close() #------也可以循环的读取文件 with open('文件','r',encoding='utf-8')as f1 : for i in f1 : print(i)
a 追加文件最后
f= open('文件',mode='a',encoding='utf-8') f.write("\nales,大王牛逼")#\n换行 f.close()
可读可写操作
w+
with open('文件',mode='r+',encoding='utf-8') as f1 : f1.write('alex sb') f1.seek(0) # 移动光标位置 不移动读的空白 s =f1.read() print(s)
r+
with open('文件',mode='r+',encoding='utf-8') as f1 : s =f1.read() f1.write('alex sb') # 因为读完后 光标在最后写入内容,不会覆盖原来的内容 print(s)
a+
with open('文件',mode='a+',encoding='utf-8') as f1 : f1.write('alex sb') f1.seek(0) s =f1.read() print(s)
4.1.5 文件操作
文件修改
# 只能读取到内存再修改 ,直接在硬盘上只能对应的字节 n = open('文件','r+',encoding='utf-8') r = n.read() read =r.replace('王豪','哈哈') n.seek(0) n.write(read) n.close() import os import time #时间模块 with open('文件',mode='r',encoding='utf-8')as f1,\ open('文件_副本',mode='w',encoding='utf-8')as f2 : for line in f1 : line=line.replace('alse','sb') f2.write(line) time.sleep(3) os.remove('文件')#删除 time.sleep(3) os.rename('文件_副本','文件')#重新命名alse,大王牛逼
seek
移动光标位置 到对应的字节 安照写入的编码
# 文件的内容是 ‘哈哈alex sbalex sbalex sb’ with open('文件',mode='r',encoding='utf-8') as f1 : f1.seek(7) s = f1.read(1) print(s) # l f1.seek(3) s = f1,read(1) print(s) #哈 特殊情况 a+ with open('文件',mode='a+',encoding='utf-8') as f1 : f1.seek(0) f1.write('alex sb') #光标移动到开头,但追加只在最后写 f1.seek(0) s =f1.read() print(s)
read
可以指定读取内容个数(字符)
# 文件的内容是 ‘哈哈alex sbalex sbalex sb’ with open('文件',mode='r',encoding='utf-8') as f1 : s = f1.read(1) print(s) # 哈
tell 返回光标的位置
with open('文件',mode='r',encoding='utf-8') as f1 : f1.seek(7) s = f1.tell() print(s)
4.1.6 断点续传
wb / rb / ab
f1 = open('文件',mode='wb') n = '王豪傻逼,寂寞了' n = n.encode('utf-8') # 忘了 看3.3.5 f1.write(n) f1.close()