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实现在线程里运行scrapy的方法
Apr 07 Python
解决Pycharm无法import自己安装的第三方module问题
May 18 Python
使用PyInstaller将python转成可执行文件exe笔记
May 26 Python
解决pandas中读取中文名称的csv文件报错的问题
Jul 04 Python
python 与服务器的共享文件夹交互方法
Dec 27 Python
python实现植物大战僵尸游戏实例代码
Jun 10 Python
Win10系统下安装labelme及json文件批量转化方法
Jul 30 Python
python 函数的缺省参数使用注意事项分析
Sep 17 Python
Python如何使用内置库matplotlib绘制折线图
Feb 24 Python
Python调用C/C++的方法解析
Aug 05 Python
python中使用 unittest.TestCase单元测试的用例详解
Aug 30 Python
Python中time标准库的使用教程
Apr 13 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
用文本文件制作留言板提示(上)
2006/10/09 PHP
PHP实现网上点歌(二)
2006/10/09 PHP
php echo()和print()、require()和include()函数区别说明
2010/03/27 PHP
php visitFile()遍历指定文件夹函数
2010/08/21 PHP
php实现memcache缓存示例讲解
2013/12/04 PHP
PHP实现的浏览器检查类
2016/04/11 PHP
mac系统下安装多个php并自由切换的方法详解
2017/04/21 PHP
PHP实现链表的定义与反转功能示例
2018/06/09 PHP
PHP常用日期加减计算方法实例小结
2018/07/31 PHP
jQueryPad 实用的jQuery测试工具(支持IE,chrome,FF)
2010/05/22 Javascript
将数字转换成大写的人民币表达式的js函数
2014/09/21 Javascript
node.js中的fs.writeSync方法使用说明
2014/12/15 Javascript
JavaScript 基本概念
2015/01/20 Javascript
bootstrap警告框示例代码分享
2017/05/17 Javascript
JavaScript切换搜索引擎的导航网页搜索框实例代码
2017/06/11 Javascript
详解node单线程实现高并发原理与node异步I/O
2017/09/21 Javascript
浅谈Node.js之异步流控制
2017/10/25 Javascript
浅析JS抽象工厂模式
2017/12/14 Javascript
vue多页面开发和打包正确处理方法
2018/04/20 Javascript
JavaScript中call和apply方法的区别实例分析
2018/08/03 Javascript
基于 vue-skeleton-webpack-plugin 的骨架屏实战
2019/08/05 Javascript
js实现计时器秒表功能
2019/12/16 Javascript
vue+vant使用图片预览功能ImagePreview的问题解决
2020/04/10 Javascript
python计算N天之后日期的方法
2015/03/31 Python
Python常见格式化字符串方法小结【百分号与format方法】
2016/09/18 Python
python实现猜数字小游戏
2020/03/24 Python
python实现查找所有程序的安装信息
2020/02/18 Python
python实现TCP文件传输
2020/03/20 Python
Python matplotlib 绘制双Y轴曲线图的示例代码
2020/06/12 Python
python闭包与引用以及需要注意的陷阱
2020/09/18 Python
员工拾金不昧表扬信
2014/01/09 职场文书
水果连锁超市创业计划书
2014/01/24 职场文书
德育标兵事迹材料
2014/08/24 职场文书
2016年中学法制宣传日活动总结
2016/04/01 职场文书
原生JS中应该禁止出现的写法
2021/05/05 Javascript
Win10 heic文件怎么打开 ? Win10 heic文件打开教程
2022/04/06 数码科技