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在校内发人人网状态(人人网看状态)
Feb 19 Python
详解Python中的文本处理
Apr 11 Python
python线程池threadpool实现篇
Apr 27 Python
Django forms组件的使用教程
Oct 08 Python
python调用百度地图WEB服务API获取地点对应坐标值
Jan 16 Python
使用pandas读取文件的实现
Jul 31 Python
python多线程+代理池爬取天天基金网、股票数据过程解析
Aug 13 Python
python3中利用filter函数输出小于某个数的所有回文数实例
Nov 24 Python
pytorch之ImageFolder使用详解
Jan 06 Python
Pytorch 神经网络—自定义数据集上实现教程
Jan 07 Python
Python中openpyxl实现vlookup函数的实例
Oct 28 Python
如何用python爬取微博热搜数据并保存
Feb 20 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 smarty截取中文字符乱码问题?gb2312/utf-8
2011/11/07 PHP
PHP数据库编程之MySQL优化策略概述
2017/08/16 PHP
使用PHP连接数据库_实现用户数据的增删改查的整体操作示例
2017/09/01 PHP
解决thinkphp5未定义变量会抛出异常,页面错误,请稍后再试的问题
2019/10/16 PHP
php设计模式之中介者模式分析【星际争霸游戏案例】
2020/03/23 PHP
jQuery仿京东商城楼梯式导航定位菜单
2016/07/25 Javascript
canvas绘制表盘时钟
2017/01/23 Javascript
微信小程序 选项卡的简单实例
2017/05/24 Javascript
设置cookie指定时间失效(实例代码)
2017/05/28 Javascript
js编写简单的计时器功能
2017/07/15 Javascript
微信小程序 swiper组件构建轮播图的实例
2017/09/20 Javascript
Angular入口组件(entry component)与声明式组件的区别详解
2018/04/09 Javascript
详解vue在项目中使用百度地图
2019/03/26 Javascript
详解vue开发中调用微信jssdk的问题
2019/04/16 Javascript
Vue实现固定定位图标滑动隐藏效果
2019/05/30 Javascript
layui监听下拉选框选中值变化的方法(包含监听普通下拉选框)
2019/09/24 Javascript
js实现漂亮的星空背景
2019/11/01 Javascript
[22:07]DOTA2-DPC中国联赛 正赛 iG vs Magma 选手采访
2021/03/11 DOTA
haskell实现多线程服务器实例代码
2013/11/26 Python
Python中urllib2模块的8个使用细节分享
2015/01/01 Python
python验证码识别教程之利用滴水算法分割图片
2018/06/05 Python
详解python中的线程与线程池
2019/05/10 Python
pycharm配置当鼠标悬停时快速提示方法参数
2019/07/31 Python
pytorch在fintune时将sequential中的层输出方法,以vgg为例
2019/08/20 Python
python接口调用已训练好的caffe模型测试分类方法
2019/08/26 Python
Django框架中间件定义与使用方法案例分析
2019/11/28 Python
浅析Python打包时包含静态文件处理方法
2021/01/15 Python
python线程优先级队列知识点总结
2021/02/28 Python
JAVA高级程序员面试题
2013/09/06 面试题
市级青年文明号申报材料
2014/05/26 职场文书
“向国旗敬礼”活动策划方案(4篇)
2014/09/27 职场文书
教师批评与自我批评(群众路线)
2014/10/15 职场文书
工作失职检讨书(精华篇)
2014/10/15 职场文书
百年孤独读书笔记
2015/06/29 职场文书
村官2015年度工作总结
2015/10/14 职场文书
详解CSS中的特指度和层叠问题
2021/07/15 HTML / CSS