Script for reading and writing files in Python open
Remember to call the close () method of the object after opening the relevant file with open. For example, you can use the try/finally statement to ensure that the file can be closed. The following is a detailed introduction to the relevant content of the article. I hope you will gain some benefits.
- 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 the file is opened, the file object file_object cannot execute the close () method.
Read files
Read text files
- input = open('data', 'r')
The above code is used to implement the second parameter of the script in the Python open read/write file. The default value is r.
- input = open('data')
Read Binary files
- input = open('data', 'rb')
Read all content
- 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( )
The above is an introduction to the content related to the Python open read/write file implementation script. I hope you will gain some benefits.