Python Open File (File Open)

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Copyright, without permission, is prohibited reprint


chapter


File handling is an important part of the application.

Python is included to create, read, update and delete files function.

File Handling

The key document processing functions in Python is a open()function.

open()Function takes two filenameparameters: ,mode

Open the file mode (mode) There are four kinds:

  • r - read-only mode is the default, if the file does not exist error
  • a - append mode, you can open the file in append the contents of a file, if the file does not exist, create the file
  • w - write mode, open the file content is written, if the file does not exist, create the file
  • x - Create a file, create a file, if the file exists, an error is returned

In addition, you can specify the file processing in binary mode or text mode

  • t - Text mode, the default value
  • b - binary pattern (e.g., video)

grammar

To open a file for reading, just pass the filename:

f = open("test.txt")

The above code is equivalent to:

f = open("test.txt", "rt")

Because r(read-only) and t(text) is the default, so you can not specify.

Note : Make sure the file exists, otherwise the program will report an error.

Guess you like

Origin blog.csdn.net/weixin_43031412/article/details/94380439