Python file operations,

Source: Internet
Author: User

Python file operations,

1. Open and Close a file

The open () function is used to open the file, and the close () function is used to close the file.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):

File: The name of a string or an array. The file name can be relative to the current directory or absolute path.

Mode: Specifies the file opening mode. The default value is'r'。

Character Description
'r' Open Reading (default)
'w' Open the write, first truncate the file
'x' Open for exclusive creation. failed if the file already exists
'a' Open for writing. If yes, It is appended to the end of the file.
'b' Binary Mode
't' Text mode (default)
'+' Open the disk file for update (read/write)
'U' General Line Break mode (obsolete)

 

 

 

 

 

 

 

 

 

Encoding: name used to decode or encode a file, for example, 'utf-8'

Other parameters are not commonly used.

Close (): When you use a file, you can call the close () method to close it and release all system resources it occupies.

f.close()

Example of opening or closing a file:

f=open('text.log','r',encoding= 'utf-8')f.close()

With statement:
To avoid forgetting to close a file after it is opened, you can manage the file by managing the context, for example:

with open('text.log','r',encoding= 'utf-8') as file_ex :    print(file_ex.read())    pass

You can also manage multiple files at the same time, for example:

with open('text.log','r',encoding= 'utf-8') as file_ex ,open('text2.log','r',encoding= 'utf-8') as file_ex2 :    pass

 

 

 

2. file read/write operations

3. Other 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.