Detailed explanation of using Python file operation open to read and write files to append text content examples

高洛峰
Release: 2017-03-24 17:55:39
Original
2516 people have browsed it

1.open After using open to open a file, you must 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 finally.

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


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 files, read text files input = open('data', 'r')

#第二个参数默认为r
input = open('data')
Copy after login


Read binary files input = open('data', 'rb')
Read all contents file_object = open('thefile.txt')

try:
 all_the_text = file_object.read( )
finally:
 file_object.close( )
Copy after login


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( )
Copy after login


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
Copy after login


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("\n都有是好人")
output .close( )
Copy after login


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

file_object.write(all_the_text)
file_object.close( )
Copy after login

The above is the detailed content of Detailed explanation of using Python file operation open to read and write files to append text content examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!