The file object is created using the Open function, and the following is a three-step procedure for manipulating files:
1, open the file to get the handle of the file, the handle is understood as this file
2. manipulate files through file handle, read/write file contents
3, close the file.
Attention:
There are 3 types of File open modes:
1. W Write mode, cannot read, can only write, if the file does not exist, create
2. R read mode, can not write, can only read, and the file must exist; If the file open mode is not passed, the default is R read mode
3. A append mode, can only write, add content at the end of the file
Open the file in W mode and write the contents as follows:
fp = open ('file.txt','w') fp.write (' HHH') # If the existing file is opened in W mode, the contents of the previous file will be emptied and re-written to HHH
Open the file in R mode and read the contents of the file as follows:
fp = open ('file.txt'r', encoding='utf-8 ') # the default character set for Windows is GBK and needs to be set to the utf-8,encoding parameter to specify the encoding of the file Print (Fp.read ()) #读取文件内容, the return result type is a string
Open the nonexistent file in R mode, as follows:
fp = open ('a.txt'r') # If the open file does not exist, Error: Filenotfounderror: [Errno 2] No such file or directory: ' a.txt 'print(Fp.read ())
Open the nonexistent file in a mode and write the contents as follows:
fp = open ('a.txt'a') # writes nonexistent file name, a append mode, Create fp.write ('yiy') # to add content at the end of the file if the file does not exist
Here's how the file is commonly used:
Read (), ReadLine (), ReadLines () reads the file contents operation:
fp = open ('file.txt','A +'#a + mode, the pointer at the end of the file, you need to move the pointer to the original file to read the content fp.seek (0) #多次读取文件内容时, be sure to move the cursor to the initial position, otherwise the read content is empty Print(FP.Read())#reads the contents of the file, returns a string, moves the pointer to the last position,Do not use large files, because the contents of the file will be read into memory, memory is not enough, the memory will be blown
Fp.seek (0) #将指针移动到初始位置
Print(FP.ReadLines())#read the contents of the file, return a list, the element is the data of each row, the large file is not used, because the contents of the file will be read into memory, memory is not enough, the memory will be blown
Fp.seek (0)
Print(FP.ReadLine())#reads only one line of the contents of a file, and returns a string
Large file, read file efficient operation method :
Using the Read () and ReadLines () method above to manipulate the file, it will first read all the contents of the file into memory, so that the memory of a lot of data, very card, efficient operation, is to read a row of operations, read the content is released from memory:
f = open ('file.txt' for in F: Print in this case, line is the content of each row of files, after reading a line, it will release a row of memory
Write (), Writelines () writes the file content operation:
fp = open ('file.txt','A +') FP.Write('2222'+'\ n')#when writing a file, only the string is writtenFp.Writelines(['123\n','456\n','789'])#Writelines can write a list to a filefp.seek (0)Print(Fp.readlines ())#execution Result: [' 2222\n ', ' 123\n ', ' 456\n ', ' 789 ']
Flush () Refreshes the file content buffer as follows:
import TIMEFP = open (" file.txt ", " w ) # Open file in W mode fp.write ( " Ode to Joy ") # Write file contents Fp.flush () # flush the internal buffer of the file, directly write the data of the internal buffers to the file immediately, instead of passively waiting for the output buffer to write to time.sleep (# sleep time is 30s fp.close () #
close file
Tell () to see where the cursor is:
fp = open ('file.txt','r+')Print(Fp.read ())#read file contents, execution result: ABCDEFGPrint(Fp.tell ())#to see where the cursor is located, the cursor is in the lastFp.seek (0)#move the cursor to the initial positionPrint(Fp.tell ())#after moving the cursor to the initial position, see where the cursor is locatedFp.seek (2)#move the cursor to the 2nd bitPrint(Fp.tell ())#after moving the cursor to the initial position, look at where the cursor is, and the cursor in the second positionFp.seek (0, 2)#move the cursor to the very endPrint(Fp.tell ())#after moving the cursor to the initial position, look at where the cursor is located, at the very end of the cursor
Truncate (size) intercepts the content of a specified length:
fp = open ('file.txt'r+') # The contents of the File.txt file are ABCDEFGprint(Fp.tell ())#fp.truncate () #若没有指定size, Empty the contents of the file Fp.truncate (3) # Pass in the size, which means to truncate the 3-bit characters from 0, the remainder of the purge fp.seek (0) Print(Fp.read ()) # execution Result: ABC
With usage, after opening the file, it can be closed without manual closing, when the file is not operated automatically, as follows:
# with usage open (filename) as Alias, the default open mode is R mode with open ('file.txt') as FP : Print(Fp.read ())
To open multiple files using with, use the following notation:
With open ('file.txt') as FP, open ('a.txt') as FW: for inch fp: Print (line) Print (Fw.readlines ())
Modify the file, there are two ways, one is to read all the contents of the file into memory, and then empty the original file content, re-write the new content, the second is to write the modified file content into a new file:
The first type:
fp = open ('file.txt','A +') Fp.seek (0) Res= Fp.read ()#The return result type is a string and the pointer is in the last faceFp.seek (0)#move the pointer to the initial positionFp.truncate ()#Empty file ContentsNew_res = Res.replace ('a','Hello')#Replace a string with Hello, replace with new string contentFp.write (New_res)#write the replaced content to a file
The second type:
ImportOSFP= Open ('file.txt','A +') Fp.seek (0) FW= Open ('a.txt','W')#opens a second file, specifically written to the replaced file contents forLineinchFp:#directly loops the file object, looping through the contents of each line of the fileNew_res = Line.replace ('Hello','666')#Replace Hello with 666, replace with new string contentFw.write (New_res)#write the modified content to a second fileFp.close ()#close file, no more read and write operation after closingfw.close () os.remove ('file.txt')#Delete Replace previous fileOs.replace ('a.txt','file.txt')#Replace the new file name with the deleted file name
ImportOswith Open ('file.txt') as FP, open ('a.txt','W') as FW: forLineinchFp:new_res= Line.replace ('666','Hello') Fw.write (new_res) os.remove ('file.txt') Os.replace ('a.txt','file.txt')
The following table lists the functions commonly used by file objects:
| Serial Number |
Method and Description |
| 1 |
File.close () Close the file. The file can no longer read and write after closing. |
| 2 |
File.flush () Refreshes the file internal buffer, directly writes the internal buffer data immediately to the file, rather than passively waits for the output buffer to write. |
| 3 |
File.fileno () Returns an integer that is a file descriptor (Descriptor FD Integer) that can be used in some of the underlying operations, such as the Read method of the OS module. |
| 4 |
File.isatty () Returns True if the file is connected to an end device, otherwise False is returned. |
| 5 |
File.next () Returns the next line of the file. |
| 6 |
File.read ([size]) Reads the specified number of bytes from the file, if none is given or is negative. |
| 7 |
File.readline ([size]) Reads the entire line, including the "\ n" character. |
| 8 |
File.readlines ([Sizehint]) Reads all rows and returns a list, and if given sizeint>0, returns a row with a sum of approximately sizeint bytes, the actual read value may be larger than sizhint because the buffer needs to be populated. |
| 9 |
File.seek (offset[, whence]) Set the current location of the file |
| 10 |
File.tell () Returns the current location of the file. |
| 11 |
File.truncate ([size]) Intercepts the file, the truncated byte is specified by size, and the default is the current file location. |
| 12 |
File.write (str) Writes a string to the file without a return value. |
| 13 |
File.writelines (Sequence) Writes a list of sequence strings to the file and adds a newline character to each line if a line break is required. |
Python file operations