1.open you must remember to call the close () method of the file object when you open the file using open. For example, you can use the Try/finally statement 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 a try block because the close () method cannot be executed by the file object File_object when an exception is opened.
2. read file read text file input = open (' Data ', ' R ')
#第二个参数默认为r
input = 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 fixed byte file_object = open (' Abinfile ', ' RB ')
Try: While
True:
chunk = File_object.read (m)
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 traverse the file object to get each line:
For line in File_object:
process Line
3. write file write 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 ("All have good people")
output. Close ()
Write Data File_object = open (' Thefile.txt ', ' W ')
File_object.write (All_the_text)
file_object.close ()
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.