python--file Operations

Source: Internet
Author: User

The open function , which is used for file processing

When working with files, you typically need to go through the following steps:

    • Open File
    • Manipulating files

First, open the file

1 文件句柄 =open(‘文件路径‘‘模式‘)

When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.

The mode of opening the file is:

    • R, read-only mode "default"
    • W, write-only mode "unreadable; not exist" created; empty content;
    • X, write-only mode "unreadable; not present, create, present error"
    • A, append mode "readable; not present, create; append content only;"

"+" means you can read and write a file at the same time

    • r+, read and write "readable, writable"
    • w+, write "readable, writable"
    • x+, write "readable, writable"
    • A +, write "readable, writable"

"B" means to operate in bytes

    • RB or R+b
    • WB or W+b
    • XB or W+b
    • AB or A+b

Note: When opened in B, the content read is byte type, and the byte type is also required for writing

Second, the operation

Python2 Python3

Iii. Management Context

To avoid forgetting to close a file after opening it, you can manage the context by:

123 with open(‘log‘,‘r‘) as f:           ...

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

In Python 2.7 and later, with also supports the management of multiple file contexts simultaneously, namely:

12 with open(‘log1‘) as obj1,open(‘log2‘) as obj2:    pass

python--file Operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.