天天看點

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)