Python file operations, open read/write files, append text content instances,
1. After open is used to open a file, 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 at last.
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.
2. Read the text file input = open ('data', 'R ')
# The second parameter defaults to rinput = open ('data ')
Read Binary file input = open ('data', 'rb ')
Read all content file_object = open('thefile.txt ')
try: all_the_text = file_object.read( )finally: file_object.close( )
Read the fixed byte 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 row list_of_all_the_lines = file_object.readlines ()
If the file is a text file, you can directly traverse the file object to get each line:
for line in file_object: process line
3. Write a file to write a 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 are good guys") output. close ()
Write Data file_object = open('thefile.txt ', 'w ')
file_object.write(all_the_text)file_object.close( )
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.