python 逐行写入文件
One of the primary reasons people use Python is for analyzing and manipulating text. If your program needs to work through a file, it is usually best to read in the file one line at a time for reasons of memory space and processing speed. This is best done with a while loop.
人们使用Python的主要原因之一是分析和处理文本。 如果您的程序需要遍历一个文件,出于内存空间和处理速度的原因,通常最好一次读取一行文件。 最好使用while循环来完成。
用于逐行分析文本的代码示例 ( Code Sample for Analyzing Text Line by Line )
fileIN = open(sys.argv[1], "r")
line = fileIN.readline()
while line:[some bit of analysis here]
line = fileIN.readline()
This code takes the first command line argument as the name of the file to be processed. The first line opens it and initiates a file object, "fileIN." The second line then reads the first line of that file object and assigns it to a string variable, "line." The while loop executes based on the constancy of "line." When "line" changes, the loop restarts. This continues until there are no more lines of the file to be read. The program then exits.
此代码将第一个命令行参数用作要处理的文件的名称。 第一行将其打开,并启动文件对象“ fileIN”。 然后,第二行读取该文件对象的第一行,并将其分配给字符串变量“ line”。 while循环根据“线”的恒定性执行。 当“行”更改时,循环重新启动。 这将继续进行,直到没有更多行要读取的文件为止。 然后程序退出。
Reading the file in this way, the program does not bite off more data than it is set to process. It processes the data it does input faster, giving its output incrementally. In this way, the memory footprint of the program is kept low, and the processing speed of the computer does not take a hit. This can be important if you are writing a CGI script that may see a few hundred instances of itself running at a time.
以这种方式读取文件,程序不会占用比设置要处理的更多的数据。 它处理确实输入的数据,从而逐渐增加其输出。 这样,程序的内存占用量保持较低,并且计算机的处理速度不会受到影响。 如果编写的CGI脚本一次可能运行数百个实例,那么这可能很重要。
有关Python中“ While”的更多信息 ( More About "While" in Python )
The while loop statement repeatedly executes a target statement as long as the condition is true. The syntax of the while loop in Python is:
只要条件为真,while循环语句就会重复执行目标语句。 Python中 while循环的语法为:
while expression:
statement(s)
The statement may be a single statement or a block of statements. All the statements indented by the same amount are considered to be part of the same code block. Indentation is how Python indicates groups of statements.
该语句可以是单个语句或语句块。 缩进相同数量的所有语句均被视为同一代码块的一部分。 缩进是Python如何指示语句组。
翻译自: https://www.thoughtco.com/analyze-a-file-with-python-2813717
python 逐行写入文件