Explain the file operation methods in Python

Time:2021-9-27

1: Open mode of file

After understanding the character encoding, we all know that files are encoded into binary in a certain standard and stored in the hard disk. In the default opening mode of the file, f = open (‘a.txt ‘,’ RT ‘, encoding =’utf-8’), where t means that the file is opened in text mode. After the application sends a data request to the operating system, the operating system reads the binary encoding on the hard disk, Then it is returned to the application, and the encoding is decoded into the characters we see through the open method; If the file is opened in B mode, the open method will not process the binary data returned by the operating system, but print directly.

?
1
f = open('a.txt','rt',encoding='utf-8')

T means that the file is opened in text mode. After the application sends a data request to the operating system, the operating system reads the binary code on the hard disk and returns it to the application. The code is decoded into the characters we see through the open method. When the file is opened in B mode, the operating system returns a string of binary numbers directly

There are three ways to open files:

Read only mode: ‘R’

Write only method: ‘W’

Append mode: ‘a’

If you open a file in byte mode, you should pay attention to:

Be sure to write ‘B’. The file can only be opened in the form of Rb, WB and AB, and ‘B’ cannot be omitted.

?
1
2
3
4
5
6
f = open('a.txt','rb'
f = open('a.txt','wb')
f = open('a.txt','ab')
#Wrong writing
f = open('a.txt','r') #If it is not indicated that it is opened in B mode, this writing method is opened in the default text mode
f = open('a.txt','rb',encode = 'utf-8') #B mode is on, and the encoding method cannot be passed in

In byte mode, all reads and writes are in bytes. If you want to write characters, you need to write them in byte type after encoding

?
1
2
f = open('a.txt','wb')
f.write('you ha'.encode('utf-8'))

Note: for non text files, we can only use byte mode, “B” means to operate in byte mode (and all files are stored in byte mode. Using this mode, we do not need to consider the character encoding of text files, JGP format of picture files and avi format of video files)

2: Operation in byte mode

Open non text file in byte mode

?
1
2
3
4
5
6
7
8
9
10
with open('1.jpg', 'rb') as f: #Open file in read-only mode
  data = f.read()       #Read all the contents of the file and assign it to the variable data
print(data)           #Print the variable, and we get the result in the form of B '\ XFF \ xd8 \ XFF \ xe0 \ X00
print(type(data))        #Type of variable < class' bytes' >
 
with open('1.jpg','rb') as f:
    data = f.read()
print(type(data))
print(data.decode('utf-8'))   #Decode the read encoding to UTF-8 standard
                 #The encoding method of the picture file is not UTF-8, so it cannot be decoded. The program reports an error

To open a text file in byte mode:

?
1
2
3
4
5
6
7
8
with open('db.txt', 'rb') as f:
  data = f.read()
print(data)         #What prints out is a string of binary numbers
print(data.decode('utf-8')) #Decoding binary numbers with UTF-8 standard
print(type(data))      #It can display characters that human beings can understand on the screen
 
with open('db.txt', 'wb') as f:
  f.write('hello \ n'.encode('utf -8'))

When opening a file in bytes, the operation of the file is based on binary

3: Modification of documents

The modification of files is not the erasure and rewriting we intuitively feel. Based on the characteristics of the hard disk, the modification of any file is the coverage of the original content by the new content. The concept of modification exists in memory. When the application starts, it requests the operating system to read data from the hard disk, and the read data runs in memory. At this time, our operations on the application modify the data content on the class memory, but do not affect the data of the hard disk. When we click save, the new data will overwrite the original data. At this time, the modification of the file is completed.

Modification method 1:
1: read all the contents of the file first
2: modify in memory
3: overwrite and write the modified content to the hard disk

?
1
2
3
4
5
6
with open("db.txt", "r", encoding="utf-8") as f:  #Open file
  data = f.read()                #Read all contents of the file
  data = data.replace("Hello:", "======")    #Modify file content
  
with open("db.txt", "w", encoding="utf-8") as f:  #Open in 'W' mode and empty the file
  f.write(data)                 #Write the modified data to

Modification method 2:

1: open source file in read mode
2: open a new file by writing

?
1
2
3
4
5
6
7
8
9
10
11
import os #Introducing OS module
 
with open('a.txt', 'r', encoding='utf-8') as read_f, \
    open('new.txt', 'w', encoding='utf-8') as new_f: #Open files at the same time
  for line in read_f:                  #Loop original file content
    if 'hello' in line:
      line = line.replace('hello', 'ha ha ha ha ha') #Replace source file contents
    new_f.write(line)                #Write the contents recycled from the original file to the new file,
    
os.remove('a.txt')                   #Call the OS module function to delete the original file
os.rename('new.txt', 'a.txt')              #Rename new file

The above is a detailed explanation of the file operation in Python. For more information about Python file operation, please pay attention to other relevant articles in developepper!

Recommended Today

I want to discuss canvas 2D and webgl with you

background This article is included inData visualization and graphicsspecial column As mentioned above, I wrote my first column and realized a simple program for the cognition of graphics and visualization. It was originally intended that the follow-up sequence has focused on the algorithm and rendering direction. However, based on the students’ feedback on obscure problems […]