Home>Article>Backend Development> Detailed explanation of using Python file operation open to read and write files to append text content examples
1.open After using open to open a file, you must remember to call the close() method of the file object. For example, you can use the try/finally statement to ensure that the file can be closed finally.
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )
Note: The open statement cannot be placed in the try block, because when an exception occurs when opening the file, the file object file_object cannot execute the close() method.
2. Read files, read text files input = open('data', 'r')
#第二个参数默认为r input = open('data')
Read binary files input = open('data', 'rb')
Read all contents file_object = open('thefile.txt')
try: all_the_text = file_object.read( ) finally: file_object.close( )
Read fixed bytes file_object = open('abinfile', 'rb')
try: while True: chunk = file_object.read(100) if not chunk: break do_something_with(chunk) finally: file_object.close( )
Read each line list_of_all_the_lines = file_object.readlines( )
If the file is a text file, you can also directly traverse the file object to get each line:
for line in file_object: process line
3. Write file Write text file output = open( 'data.txt', 'w')
Write binary file output = open('data.txt', 'wb')
Append write file output = open('data.txt', 'a')
output .write("\n都有是好人") output .close( )
Write data file_object = open('thefile.txt', 'w')
file_object.write(all_the_text) file_object.close( )
The above is the detailed content of Detailed explanation of using Python file operation open to read and write files to append text content examples. For more information, please follow other related articles on the PHP Chinese website!