python 逐行写入文件_如何使用Python逐行分析文件

本文介绍了使用Python进行逐行文件分析的效率优势和代码示例,强调了使用while循环的重要性,以保持低内存占用并提高处理速度。
摘要由CSDN通过智能技术生成

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 逐行写入文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值