Home >Backend Development >Python Tutorial >Python open reading and writing files to implement script code display

Python open reading and writing files to implement script code display

巴扎黑
巴扎黑Original
2017-05-21 18:54:021687browse

File operations in Python can be done through the open function, which is indeed very similar to fopen in C language. Obtain a file object through the open function, and then call read(), write() and other methods to read and write the file.

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

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

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

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

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 obtain each line:

for line in file_object:
    process line

3. Write file

Write text file

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

Write multiple lines

file_object.writelines(list_of_text_strings)

Note that calling writelines to write multiple lines will have higher performance than using write to write in one go.

The above is the detailed content of Python open reading and writing files to implement script code display. For more information, please follow other related articles on the PHP Chinese website!

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