Python file operations open read and write files append text content instances

  • 2020-05-17 05:53:35
  • OfStack

1.open must remember to call the close() method of the file object after opening the file with open. For example, you can use the try/finally statement to make sure you close the file at the end.


file_object = open('thefile.txt')
try:
 all_the_text = file_object.read( )
finally:
 file_object.close( )

Note: you cannot put the open statement in the try block, because the file object file_object cannot execute the close() method when an exception occurs when you open the file.

2. Read file read text file input = open('data', 'r')


# The first 2 The default value is r
input = open('data')

Read the base 2 file input = open('data', 'rb')

Read everything file_object = open(' thefile.txt ')


try:
 all_the_text = file_object.read( )
finally:
 file_object.close( )


Read 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 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 a file write a text file output = open(' data.txt ', 'w')

Write the base 2 file output = open(' data.txt ', 'wb')

Append write file output = open(' data.txt ', 'a')


output .write("\n There are good people ")

output .close( )

Write data file_object = open(' thefile.txt ', 'w')


file_object.write(all_the_text)
file_object.close( )

Related articles: