Comparison of Python advanced application instances: calculate the maximum row length in a large file efficiently

Source: Internet
Author: User
When operating on large files frequently used by many processes, you should release file resources (f. close (), only in this way can it be regarded as an efficient code. Next we will analyze the advantages and disadvantages of the three methods. The first two methods mainly use list parsing, with slightly poor performance, in the last example, the generator expression saves more memory than list parsing.

List Parsing is similar to generator expressions:

List Parsing

[Expr for iter_var in iterable if cond_expr]

Generator expression

(Expr for iter_var in iterable if cond_expr)

Method 1: original

The Code is as follows:


Longest = 0
F = open (FILE_PATH, "r ")
AllLines = [line. strip () for line in f. readlines ()]
F. close ()
For line in allLines:
Linelen = len (line)
If linelen> longest:
Longest = linelen

Method 2: Concise

The Code is as follows:


F = open (FILE_PATH, "r ")
AllLineLens = [len (line. strip () for line in f]
Longest = max (allLineLens)
F. close ()

Disadvantage: when one row iterates f, the list parsing needs to read all the lines of the file into the memory, and then generate a list

Method 3: The simplest and most memory-saving

The Code is as follows:


F = open (FILE_PATH, "r ")
Longest = max (len (line) for line in f)
F. close ()

Or

The Code is as follows:


Print max (len (line. strip () for line in open (FILE_PATH ))

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.