Home >Backend Development >Python Tutorial >Getting Started with Python Reading and Writing Files

Getting Started with Python Reading and Writing Files

巴扎黑
巴扎黑Original
2016-12-07 11:19:581136browse

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

Statement:
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
Previous article:python shelve moduleNext article:python shelve module