In python, we can () method to open files open and process the contents of the file with the built-in method.
Note that, open () by default (when the write method of execution) and then automatically converted to binary storage. So open command is stored on the basis of the binary.
4.1 The basic file operations
obj = open(file='路径',mode='模式',encoding='编码')
obj.write() # 可写模式下
obj.read() # 可读模式下
obj.close()
4.2 Open mode
- String operations
- r/w/a
- r+/w+/a+
- Direct binary operation
- rb/wb/ab
- r+b/w+b/a+b
4.3 File Operations
read () # read into memory
read (2) represents the r Mode 2 before reading two characters (not bytes), when rb mode, the byte is read 2
The write (str) #w mode, writes the string
Wb is the binary write mode, it needs to decode the binary string write:
'obj.write(你好'.decode(utf-8))
- seek (byte position of the cursor) are open mode ignoring bytes #
- tell () # Get the byte at the current cursor position
flush () # forced to write the memory data to the hard disk brush, equivalent to the hard disk
4.4 file is closed
File is not closed, it will be a waste of resources. Sometimes forget to write code when close ()
Recommended File Open method: with open(file='路径',mode='模式',encoding='编码') as f: # 相当于 f = open(file='路径',mode='模式',encoding='编码') data = read() # 下一行会自动缩进, # 缩进里的代码执行完毕后自动关闭
while opening a plurality of files:with open(file='路径',mode='模式',encoding='编码') as f1,open(file='路径',mode='模式',encoding='编码') as f2:
4.5 modify file
Write to a file can not be inserted (hard disk write rules)
so when you want to insert, you need to put all the contents of the file is read into memory, then after re-modify write all.
- Large files modified
if the file is too large. We can use a temp file as a transitional document.
Read the first line of the file (or a certain number of bytes), the memory modify, write mode A temp file.
After writing all file temp, temp file os.replace () to overwrite the original file.
## 一边读行,一边修改,一边写入新文件
import os
old_file = r'C:\Users\kouneli\Desktop\python\temp\test.txt'
new_file = r'C:\Users\kouneli\Desktop\python\temp\test_new.txt'
f = open(old_file,'r')
f_new = open(new_file,'a')
old_str = 'o'
new_str = 'K'
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
f_new.write(line)
f.close()
f_new.close()
os.replace(new_file,old_file) # 吧新文件名字改成源文件的名字,就把之前的覆盖掉了。 mac使用os.rename()