zoukankan      html  css  js  c++  java
  • 一个删除文件夹中源代码中文本中指定内容的脚本

    有时可能会遇到这么一种情况,项目的文件夹中嵌套文件夹,我们的源代码按模块分布在不同层级的文件目录里

    每个文件里都有相同的内容。我们想去掉这些信息,或者添加一些信息。

    我们该怎么样做呢?

    python可以很方便的帮我们实现

    批量删除重复内容的思路:

    step1、获取根目录下所有文件的路径

    step2、针对每一文件的路径,读出文件内容。

    step3、新建一个读操作和一个写操作。

    step4、读操作分行读取数据,写操作根据读操作的各行信息判断是否要删除该行,写入文件。

     1 #!usr/lib/env python3
     2 #coding=utf-8
     3 import codecs  
     4 import os, shutil
     5 #str 保证路径中有中文也能被正确读取
     6 root_path = str("/xxx/files")
     7 files = []
     8 def list_file(path):
     9     print("find all file pathes")
    10     for parent, dirnames, filenames in os.walk(path):
    11         for filename in filenames:
    12             if filename.endswith('.cpp') or filename.endswith('.h') :
    13                 file_path = os.path.join(parent, filename)
    14                 print("文件名 : %s" % filename)
    15                 print("完整路径 : %s
    " % file_path )
    16                 files.append(file_path)
    17     return files
    18 def delete_lines_in_file(path):
    19     #codecs.open 比open好用的地方在于 打开文件 不会包编码错误
    20     with codecs.open(path,'r',encoding= 'utf-8') as f:
    21         lines = f.readlines()
    22         # print(lines)
    23     with codecs.open(path,'w',encoding = 'utf-8') as f_w:
    24         for line in lines:
    25             print(" line %s" % line)
    26             if  "some thing appear in every file"  in line:
    27                 print("delete line %s" % line)
    28                 continue
    29             else:
    30                 f_w.write(line)
    31 
    32 if __name__ == '__main__':
    33     print("start...")
    34     files = list_file(root_path)
    35     for file in files:
    36         delete_lines_in_file(file)
    37     print("end...")

    批量增加待续。。。

  • 相关阅读:
    迁移数据到历史表,减少业务表中数据压力 Mysql
    windows server tomcat服务器部署内存占用高问题
    MySQL基于左右值编码的树形数据库表结构设计
    windows server 远程桌面连接问题。
    mysql数据库 ,java 代码巧妙结合提升系统性能。
    用户管理
    组管理命令--groupadd.groupmod.groupdel.gpasswd
    用户管理命令--passwd,usermod,userdel
    用户管理命令--useradd
    用户管理文件
  • 原文地址:https://www.cnblogs.com/wjw-blog/p/9212925.html
Copyright © 2011-2022 走看看