This section focuses on
-
Master the methods of reading, writing and modifying documents
-
Master the difference between the processing mode of the document
One. File read
? ? 1. Read all content
# disposable Read file f = open ("test.txt",'r', encoding=' gbk'= f.read ()print(data)
F.close ()
? 2. Read by line
# read by line f = open ("test.txt",'r', encoding=' GBK ' = f.readline ()print(data,end=")
F.close ()
? ? 3. Cyclic reading
# loop read f = open ("test.txt",'r', encoding=' GBK ' ) for in F: print(line,end=")
F.close ()
? 4. Binary Read
# Binary read f = open ("test.txt",'rb'= f.read ()print(Data.decode ('gbk'))
F.close ()
? 5. Read by character
#read by Bytef = open ("Test.txt",'R', encoding='GBK') Data= F.read (1)Print(data)
F.close () F= Open ("Test.txt",'R', encoding='GBK') Data= F.readline (2)Print(data)
F.close ()Two. File Write
? 1. Empty the original content to write
# empty the original content to write f = open ('test.txt','w', encoding=' gbk') f.wirte (' new content, World ') f.close () # Close and save
? ? 2. Additional content
# empty the original content to write f = open ('test.txt','a', encoding=' gbk') f.wirte (' new content, World ') f.close () # Close and save
? 3. Binary Write
# empty the original content to write f = open ('test.txt','wb') F.wirte ( ' new content, World '. Encode ('gbk')) f.close () # Close and save
? 4.flush Save
# Flush Strong Brush Save content f = open ('test2.txt','w', encoding= 'gbk') f.write (' new content, World 3') F.flush () # Save Content # f.close ()
Three. File modification
? ? 1. One-time modification, CPU usage
# disposable modification f = open ("test.txt",'r+', encoding=' GBK ' == data.replace ('Zi',' son ' ) f.write (data) f.close ()
2. Read-side change, occupy the hard drive
#while reading and changingImportOsf_name="Test.txt"F_temp_name="Test_temp.txt"F= Open (F_name,'R', encoding='GBK') F_temp= Open (F_temp_name,'W', encoding='GBK') forLineinchF:f_temp.write (Line.replace ('Child','Zi')) F.close () F_temp.close () os.replace (f_temp_name,f_name)
Python Learning Path IV: File processing