python read and write functions

1.open

After using open to open a file, be sure to call the close() method of the file object. For example, try/finally statements can be used to ensure that the file is finally closed.

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

2. Read the file

input = open( ' data ' , ' r ' )  
 #The second parameter defaults to r   
input = open( ' data ' )  

read binary file

input = open('data', 'rb')

read all

1 file_object = open('thefile.txt')  
2 try:  
3   all_the_text = file_object.read( )  
4 finally:  
5   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 a file

write text file
output = open('data', 'w')

write binary file
output = open('data', 'wb')

Append write to file
output = open('data', 'w+')

write data

file_object = open('thefile.txt', 'w')  
file_object.write(all_the_text)  
file_object.close( )  

write multiple lines

file_object.writelines(list_of_text_strings)

Note that calling writelines to write multiple lines will perform better than using write to write at once

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325024625&siteId=291194637