Python file operations

Source: Internet
Author: User

Procedure for file operation

    1. Open the file, get the file handle and assign a value to a variable
    2. Manipulating a file with a handle
    3. Close File

Basic operations

12345678 =open(‘lyrics‘#打开文件first_line = f.readline()print(‘first line:‘,first_line) #读一行print(‘我是分隔线‘.center(50,‘-‘))data =f.read()# 读取剩下的所有内容,文件大时不要用print(data) #打印文件f.close() #关闭文件

The mode of opening the file is:

    • r, read-only Mode (default).
    • w, write-only Mode. "unreadable; not exist; create; Delete content;"
    • a, Append Mode. "readable; not exist" create; "only append content;"

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

    • r+, can read and write Files. "readable; writable; can be added"
    • w+, Write and read
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"b" means processing binary files (E.G. ftp send upload ISO image file, Linux can be ignored, Windows process binary file should be Labeled)

    • Rb
    • Wb
    • Ab

With statement

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.

After Python 2.7, 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

Related Article

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.