Python修改文件往指定行插入内容的实例


Posted in Python onJanuary 30, 2019

需求:批量修改py文件中的类属性,为类增加一个core = True新的属性

原py文件如下

a.py

class A():
  description = "abc"

现在有一个1.txt文本,内容如下,如果有py文件中的description跟txt文本中的一样,则增加core属性

1.txt

description = "abc"
description = "123"

实现思路:

1.需要遍历code目录下的所有py文件,然后读取所有行数内容保存到lines列表中

2.遍历每个文件的每一行,匹配1.txt中的description,如果匹配中,就返回行号

3.往lines列表中根据行号插入要增加的新属性

4.重新写回原文件,达到修改文件的目的

如果修改成功后,效果应该是这样的

a.py

class A():
  description = "abc"
  core = True

实现代码:

import os

original_folder = 'E:\\code\\'


core_list = []

count = 0

# if the description is in the current line
def isMatchDescription(line_buffer):
  global core_list

  # if not catch the core_list in global, reload it.
  if not core_list:
    with open("./core.txt","r") as f:
      core_list = f.readlines()

  # if match the core description
  for des in core_list:
    if line_buffer.strip() == des.strip():
      return True
  return False



def modifySignatures():
  for dirpath, dirnames, filenames in os.walk(original_folder):
    for filename in filenames:
      modifyFile(os.path.join(dirpath,filename))

def modifyFile(filename):

  global count
  #print "Current file: %s"% filename
  lines = []
  with open(filename,"r") as f:
    lines = f.readlines()
    hit = 0

    # Enume every single line for match the description
    for index, line in enumerate(lines):
      if isMatchDescription(line):
        hit = index
        print hit
        print "Matched file:%s" % filename
        count+=1
    if hit > 0:
      lines.insert(hit-1,'  core = True\n')
    f.close()

  # Write back to file
  with open(filename,"w") as f:
    for line in lines:
      f.write(line)
    f.close()

if __name__ == '__main__':
  modifySignatures()
  print "Modified:%d"%count

代码中的lines.insert(hit-1,' core = True\n')这一行,hit代表目标py文件的description属性的行号,我之前用的是hit+1,但是后面发现有些文件出现了语法错误,原因是py文件中有些description的值太长,导致原文件使用了代码换行符\,如下:

a.py

class A():
  description = "abc\
  aaaaabbbbb"

这样的如果修改后就变成了

class A():
  description = "abc\
  core = True
  aaaaabbbbb"

为了避免这个bug,后面我才改成了hit-1

lines.insert(hit-1,' core = True\n')

这样修改的py文件后就是这样的效果

class A():
  core = True
  description = "abc\
  aaaaabbbbb"

以上这篇Python修改文件往指定行插入内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python文件夹与文件的操作实现代码
Jul 13 Python
Python中的__slots__示例详解
Jul 06 Python
python 将字符串转换成字典dict的各种方式总结
Mar 23 Python
Linux下安装python3.6和第三方库的教程详解
Nov 09 Python
在Python中构建增广矩阵的实现方法
Jul 01 Python
python try except返回异常的信息字符串代码实例
Aug 15 Python
python爬虫多次请求超时的几种重试方法(6种)
Dec 01 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
Python数据模型与Python对象模型的相关总结
Jan 26 Python
如何用 Python 制作一个迷宫游戏
Feb 25 Python
Python初识逻辑与if语句及用法大全
Aug 07 Python
详解Python中*args和**kwargs的使用
Apr 07 Python
python学生管理系统
Jan 30 #Python
selenium+python截图不成功的解决方法
Jan 30 #Python
python列表使用实现名字管理系统
Jan 30 #Python
Python基本socket通信控制操作示例
Jan 30 #Python
Python mutiprocessing多线程池pool操作示例
Jan 30 #Python
Python多线程处理实例详解【单进程/多进程】
Jan 30 #Python
Python读取Pickle文件信息并计算与当前时间间隔的方法分析
Jan 30 #Python
You might like
PHP生成网页快照 不用COM不用扩展.
2010/02/11 PHP
php生成随机字符串可指定纯数字、纯字母或者混合的
2014/04/18 PHP
PHP CURL 内存泄露问题解决方法
2015/02/12 PHP
学习php设计模式 php实现桥梁模式(bridge)
2015/12/07 PHP
PHP 500报错的快速解决方法
2016/12/14 PHP
jquery 读取页面load get post ajax 四种方式代码写法
2011/04/02 Javascript
jWiard 基于JQuery的强大的向导控件介绍
2011/10/28 Javascript
js触发asp.net的Button的Onclick事件应用
2013/02/02 Javascript
javascript 自定义回调函数示例代码
2014/09/26 Javascript
基于jQuery实现的无刷新表格分页实例
2016/02/17 Javascript
JS两个数组比较,删除重复值的巧妙方法(推荐)
2016/06/03 Javascript
JS中使用变量保存arguments对象的方法
2016/06/03 Javascript
JS上传图片预览插件制作(兼容到IE6)
2016/08/07 Javascript
细数JavaScript 一个等号,两个等号,三个等号的区别
2016/10/09 Javascript
JS实现直接运行html代码的方法
2017/03/13 Javascript
d3.js实现立体柱图的方法详解
2017/04/28 Javascript
Vue.2.0.5实现Class 与 Style 绑定的实例
2017/06/20 Javascript
微信小程序实现表单校验功能
2020/03/30 Javascript
babel之配置文件.babelrc入门详解
2018/02/22 Javascript
详解Angular6 热加载配置方案
2018/08/18 Javascript
详解Vue项目中出现Loading chunk {n} failed问题的解决方法
2018/09/14 Javascript
NodeJS模块与ES6模块系统语法及注意点详解
2019/01/04 NodeJs
Node.js + express基本用法教程
2019/03/14 Javascript
vue 解决移动端弹出键盘导致页面fixed布局错乱的问题
2019/11/06 Javascript
python实现封装得到virustotal扫描结果
2014/10/05 Python
python爬虫入门教程--快速理解HTTP协议(一)
2017/05/25 Python
基于Python开发chrome插件的方法分析
2018/07/07 Python
python语音识别实践之百度语音API
2018/08/30 Python
解决pycharm回车之后不能换行或不能缩进的问题
2019/01/16 Python
Python使用mongodb保存爬取豆瓣电影的数据过程解析
2019/08/14 Python
Numpy(Pandas)删除全为零的列的方法
2020/09/11 Python
中国梦我的梦演讲稿
2014/04/23 职场文书
工人先锋号事迹材料
2014/12/24 职场文书
入党转正介绍人意见
2015/06/03 职场文书
js 数组 fill() 填充方法
2021/11/02 Javascript
MySQL Server 层四个日志
2022/03/31 MySQL