01Python basics _ 06 file read/write,
1. Read files
UseopenFunction orfileFunction to read the file, using the string of the file name as the input parameter
1 # Read File Content 2 3 f = open('test.txt ') 4 5 print (f. read () # read all file content 6 print (f. readline () # read the first line of the file 7 print (f. readlines () # returns a list. Each element represents a row of 8 9 f. close () # close a file
| Method |
Description |
| Read () |
Returns a str |
| Read (size) |
Each time you read a maximum of the specified length, return a str; In Python2, size specifies the byte length, and in Python3, size specifies the character length. |
| Readlines () |
Reads all the content of a file at a time and returns a list by row. |
| Readline () |
Read Only one row at a time |
Traverse each row in the printed file:
1 with open('song.txt', 'r', encoding='utf-8') as f:2 for line in f.readlines():3 print(line)
Or:
1 with open('song.txt', 'r', encoding='utf-8', newline='') as f:2 for line in f:3 print(line)
2. Write files
Open () open files in r mode by default. To write files, open files in w mode. When you open the file in w mode, if the file does not exist, the file is created. If the file exists, the previous content is overwritten.
1 # write File 2 3 f = open('test.txt ', 'w') # Open File 4 f. write ('Hello world! ') # Write content 5 f. close () # close the file
| File opening Mode |
Description |
| R |
Open the file in read-only mode and point the file pointer to the file header. If the file does not exist, an error is returned. |
| W |
Open the file in write-only mode and point the file pointer to the file header. If the file exists, clear its content. If the file does not exist, create |
| A |
Open the file in append-only mode and point the file pointer to the end of the file. If the file does not exist, create |
| R + |
Added the writable Function Based on r. |
| W + |
Added the readable function based on w. |
| A + |
Added the readable Function Based on. |
| B |
Read/write binary files (t by default, indicating text), which must be used in combination with the above modes, such as AB, wb, AB, AB + (this character is ignored in POSIX systems, including Linux) |
3. close the file
Closing a file ensures that the content has been written to the file. Unexpected results may occur if you do not close the file. Use close () to close the file.
Try... finally can be used to ensure that files can be closed in any way:
1 # write File 2 try: 3 f = open('test.txt ', 'W +') # Open File 4 f. write ('Hello world! ') # Write content 5 finally: 6 if f: 7 f. close () 8 print ('file has been closed .')
In fact, Python provides a safer method whenwithAfter the content of the block is completed, Python automatically calls itscloseMethods To ensure read/write security:
1 # write File 2 with open('test.txt ', 'w') as f: 3 f. write ('Hello world! ') # Write content 4 print (f. closed) # Return True