Chapter IV file operations
4.1 The basic file operations
obj = open('路径',mode='模式',encoding='编码')
obj.write()
obj.read()
obj.close()
with open...
4.2 Open mode
- r / w / a
- r+ / w+ / a+
- rb / wb / ab
- r+b / w+b / a+b
4.3 Operation
read (), read all memory
read(1)
1 represents a character
obj = open('a.txt',mode='r',encoding='utf-8') data = obj.read(1) # 1个字符 obj.close() print(data)
1 represents a byte
obj = open('a.txt',mode='rb') data = obj.read(3) # 1个字节 obj.close()
write (string)
obj = open('a.txt',mode='w',encoding='utf-8') obj.write('中午你') obj.close()
write (binary)
obj = open('a.txt',mode='wb') # obj.write('中午你'.encode('utf-8')) v = '中午你'.encode('utf-8') obj.write(v) obj.close()
seek (byte cursor position), regardless of whether the strip mode B, are processed in bytes.
obj = open('a.txt',mode='r',encoding='utf-8') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data) obj = open('a.txt',mode='rb') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data)
tell (), obtaining the byte at the current cursor position
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳转到指定字节位置 obj.read() data = obj.tell() print(data) obj.close()
flush, forced to write data to the hard disk memory
v = open('a.txt',mode='a',encoding='utf-8') while True: val = input('请输入:') v.write(val) v.flush() v.close()
4.4 close the file
Young artists
v = open('a.txt',mode='a',encoding='utf-8')
v.close()
idiot
with open('a.txt',mode='a',encoding='utf-8') as v:
data = v.read()
# 缩进中的代码执行完毕后,自动关闭文件
4.5 modify the contents of the file
with open('a.txt',mode='r',encoding='utf-8') as f1:
data = f1.read()
new_data = data.replace('飞洒','666')
with open('a.txt',mode='w',encoding='utf-8') as f1:
data = f1.write(new_data)
Large file modification
f1 = open('a.txt',mode='r',encoding='utf-8')
f2 = open('b.txt',mode='w',encoding='utf-8')
for line in f1:
new_line = line.replace('阿斯','死啊')
f2.write(new_line)
f1.close()
f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2:
for line in f1:
new_line = line.replace('阿斯', '死啊')
f2.write(new_line)