Getting Started with Python Reading and Writing Files

巴扎黑
Release: 2016-12-07 11:19:58
Original
1122 people have browsed it

1. Open the file and read all the contents

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

2. 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( )

3. Read one line of the file

f = open("D:\test\BlueSoftSetup.log","r")

try:

while True:

line = f. Readline () l if line:

Print (line)

else:

break;

finally:

f.close ();

4. output = open('data', 'w')

Write binary file

output = open('data', 'wb')


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


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

file_object.write(all_the_text)

file_object.close( )

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!