The use of the open function in Python

Source: Internet
Author: User

Use the following:

Name = open (' Errname.txt ', ' W ')
Name.readline ()
Name.close ()

  

1, look at the first line of code

Used to access the files stored on the disk, can be read and write operations, such as the "W" in the above example, this is the Errname.txt this file read operation

For example:

W: Open in write mode

A: Open in append mode

r+: Open in read-write mode

w+: Open in read-write mode

RB: Open in binary read mode

WB: Open in binary write mode

AB: Open in binary append mode

rb+: Open in binary read/write mode

wb+: Open in binary read - write mode

ab+: Open in binary append mode

2. Let's look at the second line in the previous example:

1) First look at the usage and differences of ReadLine and ReadLines:

>>> name = open (' Test.txt ', ' r ') >>> username = name.readline () >>> username ' devilf\n ' > >> username = name.readlines () >>> username[' gy\n ', ' tom\n ', ' lisa\n ', ' lebron\n ', ' Kobe ']

  

As you can see, ReadLine reads only one line of content, while ReadLines reads the contents of the file row by line

But we see that the username list of the output is not a normal list with a \ n newline character, so we need to remove it:

>>> username = [Line.strip (' \ n ') for line in Name.readlines ()]>>> username[' Devilf ', ' Gy ', ' Tom ', ' Lisa ', ' LeBron ', ' Kobe ']

  

3, the third line

In fact, after the completion of the above operation, a way to close the file, needless to say

The following is a formal explanation of the use of the open () function

One, write the file

1) write in W mode

>>> f = open (' 1.txt ', ' W ') >>> f.write (' This is a test ') 14>>> f.close () >>> g = open (' 1. TXT ', ' r ') >>> G.readline () ' This is a test '

  

2) write in Append mode

>>> f = open ('1.txt','a')>>> F.write ('2017/1208')9>>>f.close ()>>> f = open ('1.txt','R')>>> g =F.readline ()>>>g'This is a test2017/1208'

The use of the open function in Python

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.