如何在Python中逐行读取文件?

Python provides different ways in order to read a file line by line. Line by line reading a file can be useful if the file is very large and can not be stored in the memory completely to make the read operation more efficient and faster. Reading files chunk by chunk is a good way which can be also expressed by reading line by line.

Python提供了不同的方式来逐行读取文件。 如果文件很大并且不能完全存储在内存中,则逐行读取文件可能很有用,以使读取操作更高效,更快捷。 逐块读取文件是一种好方法,也可以通过逐行读取来表示。

打开文件阅读 (Open File To Read)

Before reading a file line by line we will open the file for the read operation. A file can be opened with different modes like for reading, writing, appending, reading binary data, writing binary data. In this case, our intention is to read the file in which mode is r. We will use open() function where we will provide also r mode options and the file name or path we want to read.

在逐行读取文件之前,我们将打开文件进行读取操作。 可以使用不同的模式打开文件,例如读取,写入,附加,读取二进制数据,写入二进制数据。 在这种情况下,我们的目的是读取模式为r的文件。 我们将使用open()函数,其中还将提供r模式选项以及我们要读取的文件名或路径。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line
    # here

Here we can see that we will open the file and set the file handler fp then we will read line by line in the next sections. We will use try in order to catch exceptions and errors.

在这里,我们可以看到将打开文件并设置文件处理程序fp然后在下一部分中逐行阅读。 我们将使用try来捕获异常和错误。

正确关闭打开的文件 (Close Opened File Properly)

Opening a file will allocate some resources on the systems and we should free this resource after the operations are complete. We need to close the file properly when the reading of line by line is complete. We can close the opened file with the close() method by providing the file handler. We will also use close() method inside the finally part to the try if there is an exception about opening and reading files we will close this file.

打开文件将在系统上分配一些资源,我们应该在操作完成后释放该资源。 逐行读取完成后,我们需要正确关闭文件。 通过提供文件处理程序,我们可以使用close()方法关闭打开的文件。 如果在打开和读取文件方面存在异常,我们还将在tryfinally一部分中使用close()方法,我们将关闭该文件。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line
    # here

finally:
    fp.close()

从文件读取单行 (Read Single Line From File)

Python provides 3 methods in order to read a file. read() function will read the whole file and return the content. This can be useful small files but it is very error-prone while working with big files. readline() function is the most useful function to read file line by line. readline() function will read a single line from the file and jump the cursor next file for next readline() function call. So for each readline() call the cursor of position is stored by the file handler. In the following example, we will just read a single line from the file myfile.txt with fp file handler and then close the file.

Python提供了3种方法来读取文件。 read()函数将读取整个文件并返回内容。 这可能是有用的小文件,但在处理大文件时非常容易出错。 readline()函数是逐行读取文件的最有用的函数。 readline()函数将从文件中读取一行,然后将光标跳到下一个文件以进行下一个readline()函数调用。 因此,对于每个readline()调用,位置光标都由文件处理程序存储。 在下面的示例中,我们将使用fp文件处理程序从文件myfile.txt中读取一行,然后关闭该文件。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line

    line = fp.readline()

    print(line)


finally:
    fp.close()

使用readline()方法逐行读取文件 (Read File Line By Line with readline() Method)

In this case, we will read the complete file named myfile.txt line by line by using readline() method. We will use while loop and some checks with if condition keyword. We will create an infinite loop with while True: line where we will read single line in every step. In the bottom, we will check whether the file end and there is no line to read with if not line: line and if the file is ended we end the loop with break keyword.

在这种情况下,我们将使用readline()方法逐行读取名为myfile.txt的完整文件。 我们将使用while循环和if条件关键字进行一些检查。 我们将使用while True:行创建一个无限循环,我们将在每一步中读取一行。 在底部,我们将检查文件是否结束, if not line: ,则没有行要读取if not line: line,如果文件结束,则使用break关键字结束循环。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line

    while True:

        # Read current line and put content to line
        line = fp.readline()

        #Print the line
        print(line)

        #If there is no line exit from loop
        if not line:
            break


finally:
    fp.close()

使用For循环逐行读取文件 (Read File Line By Line with For Loop)

We can also use for loop in order to read a file line by line. We will open the file named myfile.txt and iterate over the lines with for line infp` file handler. When there is no line to read the for loop will end.

我们还可以使用for循环来逐行读取文件。 我们将打开名为myfile.txt的文件,并for line in fp`文件处理程序中的for line in遍历。 当没有行可读取时,for循环将结束。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line
    for line in fp:

        #Print the line
        print(line)

finally:
    fp.close()

使用While循环逐行读取文件 (Read File Line By Line with While Loop)

We can also use while loop in order to read line by line. We will use the readline() function. We will read a single line from the file in every iteration and set to variable line and check if we have reached the end of the file.

我们也可以使用while循环来逐行读取。 我们将使用readline()函数。 我们将在每次迭代中从文件中读取一行,并将其设置为变量line并检查是否到达文件末尾。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line

    #Read the first line
    line = fp.readline()

    while line:

        #Print the line
        print(line)

        #Read next line
        line = fp.readline()


finally:
    fp.close()

将文件行转换为列表 (Convert File Lines Into List)

In some cases converting the given file lines into the list will be very beneficial. Hopefully, Python provides the readlines() method in order to read all lines from given file and then return as a list where each line is an item in the given list. In this example, we will read the file named  myfile.txt and return lines as a list named lines. We can print a specific line from the list by providing the exact index number.

在某些情况下,将给定的文件行转换为列表将非常有益。 希望Python提供readlines()方法以便从给定文件中读取所有行,然后以列表形式返回,其中每一行都是给定列表中的一项。 在此示例中,我们将读取名为myfile.txt的文件,并将行作为名为lines的列表返回。 我们可以通过提供确切的索引号从列表中打印出特定行。

#!/bin/python

try:
    fp = open('myfile.txt')
    # We will read "myfile.txt" line by line

    #Read the first line
    lines = fp.readlines()

    print(lines[0])
    print(lines[1])
    print(lines[2])
    print(lines[3])

finally:
    fp.close()
LEARN MORE  Python "with" Statement By Examples
通过示例了解更多Python“ with”语句

翻译自: https://www.poftut.com/how-to-read-a-file-line-by-line-in-python/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值