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

yipeiwu_com5年前Python基础

需求:批量修改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实现简易通讯录修改版

描述: 上一篇博客我写了一个简单的通讯录,但是还是觉得不够完美: 需要输入ID,虽然ID是主键,但是没有实现自增功能; 忘记加电话号码了; 如果插入用户名相同,则后续的查、改、删功能受到...

python中如何使用分步式进程计算详解

python中如何使用分步式进程计算详解

前言 在python中使用多进程和多线程都能达到同时运行多个任务,和多进程和多线程的选择上,应该优先选择多进程的方式,因为多进程更加稳定,且对于进程的操作管理也更加方便,但有一点是多进程...

用tensorflow实现弹性网络回归算法

本文实例为大家分享了tensorflow实现弹性网络回归算法,供大家参考,具体内容如下 python代码: #用tensorflow实现弹性网络算法(多变量) #使用鸢尾花数据集,...

Python列表的切片实例讲解

Python列表的切片实例讲解

之前讲过python列表的基本操作,我们今天继续讲解列表中的切片等操作,列表的切片就是根据索引取列表中的数据,切片并不会改变原列表。接下来跟着小编一起学习python列表的其他操作吧。...

Python发送邮件的实例代码讲解

一、邮件发送示例 邮件发送示例 flask_email及smtplib原生邮件发送示例,适用于基于Flask框架开发,但是内部设置的定时任务发送邮件/或提供离线接口发送邮件操作 1....