欢迎访问宙启技术站
智能推送

使用from_line()函数实现对文本文件中特定行的替换操作

发布时间:2023-12-26 23:38:42

from_line()函数可以用于替换文本文件中特定行的内容。下面是一个使用from_line()函数的示例:

首先,假设有一个名为"example.txt"的文本文件,内容如下:

Line 1: This is the original content of line 1.
Line 2: This is the original content of line 2.
Line 3: This is the original content of line 3.
Line 4: This is the original content of line 4.
Line 5: This is the original content of line 5.

我们希望将第3行替换为新的内容。

首先,需要导入fileinput模块和os模块,并使用from_line()函数来打开文本文件:

import fileinput
import os

with fileinput.input(files=('example.txt'), inplace=True, backup='.bak') as f:

在上述代码中,files参数指定要处理的文件名,inplace参数为True表示将直接在原文件上进行修改,而backup参数为'.bak'表示在修改时将创建一个备份文件。

接下来,使用for循环遍历文本文件的每一行,我们可以通过fileinput模块的filelineno属性获取每行的行号:

    for line in f:
        if f.filelineno() == 3:
            print("This is the new content for line 3.")
        else:
            print(line, end='')

在上述代码中,如果行号等于3,则打印新的内容,否则打印原始内容。打印时使用end=''参数来避免在每行末尾添加额外的换行符。

最后,在循环结束后,需要关闭文件:

os.remove('example.txt.bak')

在上述代码中,我们使用os模块的remove()函数删除备份文件。

完整的代码如下:

import fileinput
import os

with fileinput.input(files=('example.txt'), inplace=True, backup='.bak') as f:
    for line in f:
        if f.filelineno() == 3:
            print("This is the new content for line 3.")
        else:
            print(line, end='')

os.remove('example.txt.bak')

运行上述代码后,"example.txt"文件的第3行将被替换为新的内容:

Line 1: This is the original content of line 1.
Line 2: This is the original content of line 2.
This is the new content for line 3.
Line 4: This is the original content of line 4.
Line 5: This is the original content of line 5.

请注意,使用from_line()函数进行替换时,会直接修改原始文件,因此请确保在操作前做好适当的备份。