Usage of read (), ReadLine (), and ReadLines () in Python read-write files

Source: Internet
Author: User

There are three kinds of functions in Python that read files:

    • Read ()
    • ReadLine ()
    • ReadLines ()

However, what is the difference between them, when used in peacetime always encountered, summed up today.

0. Pre-work

First, create a new file Read.txt, for examples of actual effects

Hellowelcome to my worldyou are so clever !!!
1. Read ()

The read (size) method reads a size byte from the current location of the file, and the default (no parameter) indicates that the read to the end of the file is returned as a string object

The test procedure is as follows:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.read()    print(content)    print(type(content))

Here are two points to note:

    1. I used OS-related operations, which eliminates the hassle of having to enter the full path of the file.

    2. You have to form with open file as F: This habit, that is, after the operation is finished, let it automatically close the files.

Hellowelcome to my worldyou are so clever !!!<class ‘str‘>Process finished with exit code 0
2. ReadLine ()

Reads one line at a time, consumes less memory (for large files), and returns a String object

Test procedure:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.readline()    print(content)    print(type(content))

Output Result:

Hello<class ‘str‘>Process finished with exit code 0
3. ReadLines ()

Reads all the rows of the file, saves it in a list variable, and each behavior in the list is an element that returns a list object.

Test procedure:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.readlines()    print(content)    print(type(content))

Output Result:

[‘Hello\n‘, ‘welcome to my world\n‘, ‘1234\n‘, ‘you are so clever !!!‘]<class ‘list‘>Process finished with exit code 0

Usage of read (), ReadLine (), and ReadLines () in Python read-write files

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.