Python (io) read file
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( )
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 the file
Read the text file
input = open('data', 'r')
#The second parameter defaults to r
input = open('data')
read binary file
input = open('data', 'rb')
read everything
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
读固定字节
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 to
write a text file
output = open('data', 'w')
write binary file
output = open('data', 'wb')
Append write to file
output = open('data', 'w+')
写数据
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
写入多行
file_object.writelines(list_of_text_strings)