Seven, python development file operation

1. Open a file, set read-only (r), and assign variables
f = open("file",'r',encoding = 'utf-8')
 
    1. Read the file (the cursor will stop at the position after reading, and the next read will start from the cursor position)
    f.read() #Read the file, read the entire file at one time,
    f.read(10) #read only 10 characters
    f.readline() #Read a line of file
    f.readlines() #Turn the file into a list and read it out
    
    2. View the subscript position where the cursor of the file is located
    f.tell()
 
    3. Move the file cursor position to the beginning of the line
    f.seek(0) #The cursor moves to the position where the subscript is 0
 
    4. View the encoding of the opened file
    f.encoding
 
    5. Determine whether the file is readable, true, false
    f.readable()   
 
    6. Determine whether the cursor of the file can be moved, whether it is True or false (the terminal device file in linux cannot be moved)
    f.seekable()
 
    7. Close the file (the file will be automatically closed after the program runs, the following is the manual close)
    f.close()
 
    8. Determine whether the file is closed, if it returns True, if not false
    f.closed()
    
2. Write the file (w)
f = open("file",'w',encoding = 'utf-8') #This is to create a new file, if the original file exists, it will be replaced.
 
    1. Write the file
    f.write('----------------------')
 
    2. Write the content in the memory cache to the disk (because the operation of writing to the file is cached in the disk, if there is a requirement for the real-time content of the content, refresh it to the disk)
    f.flush()
 
    3. Truncate (delete the content after subscript 20)
    f.truncate(20)
    
3. Append the file to the operation (a)
f = open("file",'a',encoding = 'utf-8') #The file originally exists and already has content. Using append mode will append the new content to the end.
 
Fourth, read and append to the file (r+)
f = open("file",'r+',encoding = 'utf-8') #The file can be read and appended.
 
5. Write first and then read the file (w+)
f = open("file",'w+',encoding = 'utf-8') #Because an empty file was created first, there is no content, so it can only be written first)
 
Six, read the binary file (rb)
f = open("file",'rb') 
 
Seven, write to binary files (wb)
f = open("file",'wb')
 
Eight, file read cycle (read line by line, and only one line of content is saved in memory, it will not occupy a high memory space)
for  line    in    f:
        print(line)
 
 
 
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891060&siteId=291194637