How to calculate the number of lines of a file and read a certain line of content in python

Source: Internet
Author: User

1. Calculate the number of objects

The simplest way is to read the file into a large list and calculate the length of the list. if the file path is transmitted in the form of a parameter filepath, we can use only one line of code to meet our requirements:

Count = len (open (filepath, 'ru '). readlines ())

If a file is very large, the above method may be slow or even invalid. At this time, you can use a loop to process it:

Count =-1
For count, line in enumerate (open (thefilepath, 'ru ')):
Pass
Count + = 1

Another way to process large files is to calculate the number of linefeeds '\ n' (or strings containing' \ n', such as in windows ):

Count = 0
Thefile = open (thefilepath, 'rb ')
While True:
Buffer = thefile. read (8192*1024)
If not buffer:
Break
Count + = buffer. count ('\ n ')
Thefile. close ()

The 'rb' parameter is required. Otherwise, the code above will be very slow on windows.

Linecache is a function library that supports reading large files and row-based reading. Linecache reads the file into the cache in advance. If you access the file later, the file will not be read from the hard disk.

2. Read the content of a row of a file (the efficiency of a 1 GB file has been tested)

Import linecache

Count = linecache. getline (filename, linenum)


3. Use linecache To Read File Content (1 GB files have been tested, and the efficiency is acceptable)

Str = linecache. getlines (filename)

Str is a list, and each row is an element in the list.

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.