python 刪除文件某一行


python 刪除文件某一行

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/29 15:06
# @Author  : hyang
# @File    : delLine.py
# @Software: PyCharm

import sys
import os
import random
import shutil
import string


def getLine_num(filename):
    count = 0
    for index, line in enumerate(open(filename, 'rb')):
        count += 1
    return count


def remove_Line(filename, del_line):
    """
    刪除文件某一行
    :param filename:
    :param del_line:
    :return:
    """
    # 打開舊文件
    old_file = open(filename, "rb")
    # 打開新文件
    new_file = open("%s.new" % filename, "wb")

    current_line = 0
    # 定位到需要刪除的行
    while current_line < (del_line - 1):
        current_line_cont = old_file.readline()
        # 把每一行寫入新文件
        new_file.write(current_line_cont)
        current_line += 1

    # 當前光標在被刪除行的行首,記錄該位置
    seek_point = old_file.tell()

    # 設置光標位置
    new_file.seek(seek_point, 0)

    # 讀需要刪除的行,光標移到下一行行首
    line_con = old_file.readline()
    print("需要刪除行: {}".format(line_con))

    # 被刪除行的下一行讀給 next_line
    next_line = old_file.readline()

    # 連續覆蓋剩余行,后面所有行上移一行
    while next_line:
        new_file.write(next_line)
        next_line = old_file.readline()

    # 文件關閉
    old_file.close()
    new_file.close()

    # 文件備份與替換
    bak_f = filename + ''.join(random.sample(string.digits, 6))
    os.rename(filename, bak_f)  # 備份舊文件
    print("源文件備份為%s" % bak_f)
    os.rename("%s.new" % filename, filename)  # 把新文件名字改成原文件的名字,就把之前的覆蓋掉了


# def main_arg():
#     if len(v_arg) != 2:
#         # print(platform.system())
#         print_arg(v_arg)
#         print_warn("---參數輸入錯誤--")
#         print_warn("delLine 文件名 刪除行")
#     else:
#         f_name = v_arg[1].strip()
#         line_no = v_arg[2].strip()  # 刪除行
#     if not line_no.isdigit():
#         print_error("行數必須為數字" )
#     else:
#         if not os.path.exists(f_name):
#             print("%s文件不存在" % f_name)
#     else:
#         pass


def main():
    f_name = 'F:\a/logs'
    bak_f = f_name + ''.join(random.sample(string.digits, 6))
    line_no = '2'
    line_no = int(line_no)

    line_num = getLine_num(f_name)  # 獲得文件總行數
    if line_no > line_num:
        print("行數大於文件行數 " + line_num)
    else:
        print("文件總行數={},刪除第{}行" .format(line_num, line_no))
        remove_Line(f_name, line_no)


if __name__ == '__main__':
    # 獲得系統參數
    # v_arg = sys.argv
    # main_arg()
    # init(autoreset=True)  # 初始化,並且設置顏色設置自動恢復
    main()
    # print_color(Style.RESET_ALL)  # 還原默認顏色

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM