In order to better illustrate the next file modification operation, we need to learn the common methods of file operation.
I. Common methods in file processing
#! /usr/bin/env Python3#-*-coding:utf-8-*-#Write by Congcong#Flush () forces the file to be flushed from memory to the hard diskf = open ('W_flush.txt', mode='r+') F.write ("This is a forced flush of files to the hard drive! ") F.flush ()Print("To view files:", F.read ())#f.close ()#readable () to determine whether it is readablePrint(F.readable ())#Output: TrueF1 = open ("W_flush.txt", mode='W')#write operations for filesF1.write ('determine if the file is readable! ') F1.flush ()Print(F1.readable ())#Output: False (indicates that the file is not readable when writing)#readline () output one line, touch \ r or \ n Endf = open ('W_flush.txt', mode='a', encoding='GBK') F.write ('I am the first line! ') F.write ('\ n I'm the second line! ') F= Open ('W_flush.txt', mode='R', encoding='GBK')Print(F.readline ())#output: I am the first line! #Tell () returns the current position of the cursor, in bytes as the unit of measurePrint(F.tell ())#output; 14, because the encoding is GBK, GBK each Chinese character occupies two bytes, so the cursor is at the end of the first line#Seek () moves the cursor to the specified byte position, in bytes as a count unitPrint(F.seek (2))#Output: 2Print(F.readline ())#the output is the first line! Print(F.seek (4))#Output: 4Print(F.readline ())#output: First line#seekable () determine if the file can be used in Seek,linux (all documents)#Read () specifies the length in parentheses, starting at the current position, reading a few characters, and not specifying a length in parentheses, in all files, in charactersPrint(F.tell ())Print(F.seek (0))Print(F.read (2))#output: I am#truncate () truncates a file by a specified length, truncates the specified length from the beginning of the file, and at the specified length in parentheses, removing all content from the current position to the end without specifying a length#This method must be used in write modef = open ('W_flush.txt','r+', encoding='GBK')Print(F.seek (4))#output; 4Print(F.tell ())#output; 4Print(F.truncate (8))#output; 8Print(F.seek (0))#Output: 0f.close ()
Understanding the above methods, we can happily carry out the file modification operation.
Second, the file modification operation
When we open a file in read-write (r+) mode, the new content is appended to the end of the file by default.
What is this for? So what do we do if we want to modify the content in the middle?
Remember we just learned a tell () method, its unit is byte, when we read a piece of content, the cursor will follow the move, the file is finished reading, the cursor will be moved to the end,
Then write, the cursor will naturally follow the movement, after writing, the cursor will stay at the end, we can use the tell () method to verify the conjecture, print at this time the cursor position,
At this point, we want to read the contents of the file, there is no output, are blank. This explains why I can't read the additional content.
As to why the append content starts at the end, it is easy to understand that when you open a file in Append mode, the cursor is moved by default to the tail of the file before it starts writing.
And the file modification is going to use another method, the Seek () method, its role is to move the cursor to the specified position, the unit of movement is a byte, when we want to modify a place,
Using the Seek () method to move the cursor to the specified position can be modified, we can try:
#the original content of Write.txt is: This is the first file I wrote in Python!#now I'm going to change ' write ' to ' modified 'F= Open (file='Write.txt', mode='r+', encoding='GBK')Print('before modification: \ n', F.read (), F.tell ())#read the contents of the pre-modified file and print the current cursor positionF.seek (20)#move the cursor to the location after the 20th word (GBK encoding a Chinese character is 2 bytes, English is 1 bytes)F.write ('after modification')#Write the modified contentF.seek (0)#move the cursor to the beginning of the filePrint(F.tell ())#Print the current cursor positionPrint('modified: \ n', F.read (), F.tell ())#read the modified file content and print the current cursor positionf.close ()#Close File" "This is the first file I wrote in Python! 290 modified: This is the first one I modified with Python after the pieces!" "
No error, normal execution, ' write ' also has been changed to ' modified ', the file size has not changed, but also we do not want to modify the content is overwritten, which is embarrassing ...
Here's why :
This is the storage principle of the hard disk, when you save the file to the hard disk, on the hard disk zoned a space, save data, and so you next open this file, seek to a location, each change a word, is the original cover off, if you want to insert, is not possible, because the data on the hard disk will not be moved back. So the current situation, you want to insert, but become the old content will be covered out.
How about the solution?
Want to change of course, but do not modify on the hard disk, the contents of all read into memory, the data in memory can be arbitrarily deleted and modified, after the modification, the contents of all write back to the hard disk, the original data all covered out.
For example:
#-*-coding:utf-8-*-ImportOs#Import ModuleF1='Notebook.txt' #files to be modifiedF2 ='Note_new.txt' #the modified fileF_old = open (f1,mode='R', encoding='Utf-8')#Open the file to be modifiedf_new = open (f2,mode='W', encoding='Utf-8')#Write the modified fileOld_str='a' #String to modifyNew_str =' One' #the modified stringCount = 0#Statistics Modification Times forLineinchF_old:#cyclic reading ifOld_strinchLine:newline= Line.replace ('a',' One')#ReplaceCount + = 1#self-increment 1 per modification Else: NewLine=Line f_new.write (newline)#Write the modified fileF_old.close ()#Turn offf_new.close () os.replace ('Note_new.txt','Notebook.txt')#replace the old file with the contents of the new filePrint('Number of modifications:'Count#Number of modifications: 5
Python file modifications and common methods