Summary of Python file operations

1. Common methods of file operation:

1. read(): Read the rest of the entire file from the cursor position. Note that it starts from the cursor position, not necessarily the entire file.

#First read: 
f=open( ' test.txt ' , ' r ' )
 print (f.read())
f.close()                  
# Self-fear of being too sentimental and damaging the holy life, and fearing to lose the city by mistake when entering the mountain. The world is safe and full of the law, and it will live up to the Tathagata and live up to the emperor. 
Author: Cangyang Gyatso

#Second read 
f=open( ' test.txt ' , ' r ' )
f.readline()
print (f.read()) #Author         : Cangyang Gyatso 
f.close()

2. The difference between readline and readlines:

# readline() only reads one line, and then the cursor moves to the next line 
f=open( ' test.txt ' , ' r ' )
 print ( f.readline (
 ))        .The world is safe and secure, and the Tathagata lives up to the Lord. print (f.readline()) #Author      : Cangyang Gyatso 
f.close()

# readllines() reads the entire file and stores each line as an element in a list. Note that there is an exchange symbol after each element 
f=open( ' test.txt ' , ' r ' )
 print (f.readlines())    # ['I am afraid of being too sentimental and damaging the holy life, and I am afraid of falling into the mountains and ruining the city by mistake. The world The Dharma of Enlightenment and Perfection can live up to the Tathagata and the Lord.\n', 'Author: Tsangyang Gyatso\n'] 
f.close()

#Finally note: readlines is to read and write all files into memory at one time. If the file is small, it is fine, but once the file is large, it will be fatal. Large files can be read and written using the following method: 
with open( ' test.txt ' , ' r ' ) as f:
     for line in f:
         print (line.strip())

#The advantage of reading and writing in this way is to read line by line, and release it after reading, without occupying memory at all.

 

 

 3、write,writelines

f.write( ' 1111\n222\n ' ) #For text mode writing, you need to write newlines 
yourself f.write( ' 1111\n222\n ' .encode ( ' utf-8 ' )) #For b mode To write, you need to write newline characters 
yourself f.writelines([ ' 333\n ' , ' 444\n ' ]) #File mode 
f.writelines([bytes( ' 333\n ' ,encoding= ' utf-8 ' ), ' 444\n ' .encode( ' utf-8 ' )]) # b mode

 

 4. Other methods:

f.readable() #Whether the file is readable 
f.writable() #Whether the file is readable 
f.closed #Whether the file is closed f.encoding 
#If the file opening mode is b, there is no such attribute f.flush ( 
) #Immediately The file content is flushed from memory to hard disk 
f.name    #file name

 Second, the movement of the file cursor:

1. read(n) When the file is opened in text mode, it means to read n characters , and when the file is opened in b mode, it means to read n bytes

# 1. Read 
with open( ' test.txt ' , ' r ' ) as f:
     print ( f.read (4))    in text mode

# 2. Read in byte mode: 
with open( ' test.txt ' , ' rb ' ) as f:
     print (f.read(4).decode( ' gbk ' ))          # Self-fear 
#Direct output: print (f.read()) output is b'\xd7\xd4\xbf\xd6'

 

2. tell() Gets the position of the current file pointer, no parameters. return in bytes

with open('test.txt','r') as f:
    print(f.read(4)) #自恐多情
    print(f.tell())   #8

 

3. Seek() Function: used to move the file read and write pointer to the specified position.

#The prototype of the function is: file.seek(offset,whence=0) 
offset refers to the offset, whence has three values, 0, 1, 2. 0 means move to the beginning of the file, 1 refers to the current position, and 2 refers to the file end. The default is to use the default value of 0. #Note 
 : the use of parameters 1,2 must open the file in byte mode b! 

with open( ' test.txt ' , ' r ' ) as f:
     print (f.read(4)) # self- awesome 
    print (f.tell())    # 8 
    f.seek(0,0) #return       to the beginning 
    print ( f.read (4))       #selfish



with open('test.txt','rb') as f:
    print(f.read(4).decode('gbk')) #自恐
    f.seek(-4,1)
    print(f.read(4).decode('gbk'))  # 自恐


with open('test.txt','rb') as f:
    f.seek(-4,2)
    print(f.read(4).decode('gbk'))   #嘉措

 

Second, the modification of the file:

  In fact, we usually talk about fixing a certain part of a file, but it is actually not directly modifying the file, but overwriting it. The data of the file is stored on the hard disk, so there is only coverage and no modification. The modified files we usually see are simulated effects. We can use the following code to simulate this process.

import   them
with open('test.txt','r') as f ,open('test_1.txt','w') as f1:
    for line in f:
        line =line.replace( ' I am afraid of being too sentimental and damaging the holy life, and when I enter the mountain, I am afraid of ruining the city by mistake. In the world, I am safe and secure, and I am not afraid of the Tathagata nor my Lord. ' ,\
                           ' I am not afraid of being too affectionate and damaging the holy life. The law of peace and security is better than the Tathagata than the emperor. ' )
        line =line.replace( ' Cangyang Gyatso ' , ' Yo, what about writing a bug?? ' )
        f1.write(line)

os.remove('test.txt')
os.rename('test_1.txt','test.txt')

Guess you like

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