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 ))