天天看点

python 根据行号删除文件指定的行

第一种方法:

#!/usr/bin/python3

# -*- coding: UTF-8 -*-

def Del_line(file_path,line_num):

    file = open(file_path,"r")

    for num,value in enumerate(file,1):

        if num == line_num:

            with open(file_path,'r') as r:

                lines=r.readlines()

            with open(file_path,'w') as w:

                for nr in lines:

                    if value not in nr:

                        w.write(nr)

    file.close()

    return

Del_line("test.txt",2) 

第二种方法

#!/usr/bin/python3

# -*- coding: UTF-8 -*-

def Del_line(file_path,line_num):

    with open(file_path,"r") as f:

        res = f.readlines() #res 为列表

    res.pop(int(line_num)-1) #因为实际行数是从 0 开始的,所以需要 - 1

    with open(file_path,"w") as f:

        f.write("".join(res))  #将 res 转换为 字符串重写写入到文本

Del_line("test.txt",2)