Basic operations for Python files

Source: Internet
Author: User

In Python, there are four types of basic operations for a file:

1. Open File

File_obj = open ("File path", "mode") the commonly used opening file modes are:

R: Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
W: Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
A: Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
w+: Opens a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.

2. Read the contents of the file

Obj.read (): Load all content into memory at once
Obj.readlines (): Loads all content into memory at once and splits it into strings based on rows
For line in obj:
Print Line
-------------Read only one row of data at a time

3. Write the contents of the file

Obj.write (' content '): Write content to a file

4. Close the file handle

Obj.close (): Close file
Common usage:

Read
1  obj = open ("test.log","R")2    for in obj:3      print(line)4  Obj.close ()
Write
1  obj = open ("test.log","w")2  Obj.write ("This is the firstline\n")3  obj.write (  "This is thesecond line\n")4  obj.close ()
Additional
1  obj = open ("test.log","a")2  Obj.write ("This is thethree line\n")3  obj.close ()
Write read
1  obj = open ("test.log","w+")2  Obj.write ("new line\n")3  print("  data:", Obj.read ())4  obj.close ()

Attention:

1. Cannot write when reading, cannot read when writing

2. The contents of the original file will be flushed out every time you use the read-write.

3. When using the file, always remember to close it when you open it

Basic operations for Python files

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.