文件操作
操作系统
windows mac linux
双击文件
硬盘转 磁头读取数据
保存文件
硬盘转 磁头写入数据
我们在操作文件的时候其实操作的是硬盘
'''文件其实是操作系统暴露给我们可以简单快捷的操作硬盘的接口'''
绝对路径与相对路径
绝对路径
非常详细的路径描述
无论什么人什么位置都可以找到
相对路径
有一个参考
只有对应的人才可以找到
"""在中国所有的windows电脑内部默认的编码是gbk"""
with open(r'a.txt') as f:
print(f.read())
with open(r'a.txt', mode='rt', encoding='utf-8') as f, \
open(r'b.txt', mode='wt', encoding='utf-8') as f2:
pass
f = open('a.txt',mode='rt',encoding='utf-8')
print(f.read())
print('='*50)
print(f.read())
print(f.readable())
print(f.writable())
f.close()
f = open('a.txt',mode='wt',encoding='utf-8')
f.write("你好\n")
f.write("哈哈哈\n")
f.write("我擦勒\n")
f.write("你好\n哈哈哈\n我擦勒\n")
print(f.readable())
print(f.writable())
f.close()
f = open('c.txt',mode='at',encoding='utf-8')
f.write("4444\n")
f.write("555\n")
f.write("6666\n")
print(f.readable())
print(f.writable())
f.close()
with open('1.mp4',mode='rb') as f:
res = f.read()
print(res.decode('utf-8'))
with open('a.txt',mode='rb') as f:
res = f.read()
print(res.decode('utf-8'))
with open('a.txt',mode='ab') as f:
f.write("啊手动阀手动阀".encode('utf-8'))
with open('1.mp4',mode='rb') as f1,open(r'D:\1111111.mp4',mode='wb') as f2:
res = f1.read()
f2.write(res)
with open('a.txt',mode='rt',encoding='utf-8') as f:
for line in f:
print(line,end='')
with open('1.mp4',mode='rb') as f:
for line in f:
print(line)
with open('1.mp4',mode='rb') as f1,open(r'D:\1111111.mp4',mode='wb') as f2:
for line in f1:
f2.write(line)
with open('a.txt',mode='r+t',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
print(f.read())
f.write("22222222222222222222\n")
with open('a.txt',mode='w+t',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
with open('a.txt',mode='rt',encoding='utf-8') as f:
print(f.readline())
print(f.readline())
with open('a.txt',mode='wt',encoding='utf-8') as f:
f.write('hello')
f.flush()
f.seek(字节个数,0)
f.seek(字节个数,1)
f.seek(字节个数,2)
ps:只有0模式可以t下使用,其中1和2模式只能在b模式下使用,但是无论在t模式还是b模式下,移动的都是字节个数
with open('a.txt',mode='rt',encoding='utf-8') as f:
print(f.tell())
print(f.tell())
with open('a.txt',mode='rb') as f:
print(f.tell())
f.seek(9,1)
f.seek(3,1)
print(f.tell())
with open('a.txt',mode='rb') as f:
print(f.tell())
f.seek(0,2)
print(f.tell())
with open('a.txt',mode='ab') as f:
print(f.tell())
with open('test.txt', mode='r+t', encoding='utf-8') as f:
f.seek(9,0)
f.write("hello")
文件修改的原理:
把硬盘数据读入内存,在内存修改完毕后,再覆盖回硬盘
具体来说又分为两种方案
方案一:
with open('test.txt',mode='rt',encoding='utf-8') as f:
data = f.read()
with open('test.txt',mode='wt',encoding='utf-8') as f:
f.write(data.replace('egon','EGON'))
方案二:
import os
with open('test.txt',mode='rt',encoding='utf-8') as f1,\
open('.test.txt.swp',mode='wt',encoding='utf-8') as f2:
for line in f1:
f2.write(line.replace('EGON',"egon"))
os.remove('test.txt')
os.rename('.test.txt.swp','test.txt')