Easy Python file feature-operations on Rows

Source: Internet
Author: User

1. Count lines of text

The most common is readlines.

>>> handler=open (' input_file.txt ') >>> lines=handler.readlines () >>> Lenoffile=len (lines )

However, if it is a text file more than 100m, the above method is basically determined to be very slow, even can not run

So, we need other ways.

1) using cycle count, introduce enumerate method


Note: Count is starting from-1


2) If we consider the problem of performance, we use other methods

Because text files are generally n/a newline characters, we can load part of the text and calculate how many line breaks are inside.

>>> Import codecs>>> count = 0>>> the_file = Codecs.open (' input_file.txt ', ' RB ', ' Utf-8 ') > >> Try:while (True):      buffer = the_file.read (8192*1024)      if not buffer:break    




2. Read a line (take small text for example)

We usually think of loops and then go to a line to stop and print

The above example can be encapsulated as a method:


But we have a much quicker approach:

We introduce Linecache, we get a line by Getline method, but we need to note: its number of rows is starting from 0


Right here, thank you.

------------------------------------------------------------------

Click to jump 0 basic python-Catalogue



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Easy Python file feature-operations on Rows

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.