Python读取模板以及整理好的csv文件,替换模板关键字内容,生成新的脚本

工作需要,这前两天写了一个简单的Python脚本,本人是java开发,没怎么学过Python,文章仅仅作为记录学习的过程,大佬勿喷。
需求: 给定一个shell模板,替换里面@@XXX@@的内容,替换内容从Excel里面取

因为内网里面的刚装的Python环境,所以没有安装使用第三方的openpyxl库等,就把Excel转成了csv文件,使用Python自带的csv Api完成

import csv

'''
    读取csv文件时,csv文件的内容会被放进一个字典(以(key,value)键值对的形式存储数据,相当于java里面的map集合)里面
    这里读取时,csv的第一行就会被用作key值,后面每一行都通过这个key可以获取相应列的值
'''
def read_csv(csv_file):
    content = []
    try:
        with open(csv_file, 'r', newline='') as file:
            reader = csv.DictReader(file)
            for row in reader:
                content.append(row);
    except Exception as e:
        print('csv文件读取错误: ', e)
    return content

## sh模板内容替换,写入新的sh脚本文件
def write_replace_scripte(tempContent, shPath, csvContent):
    # 遍历csv文件的每一行
    for row in csvContent:
        # 获取fileName那一列的值
        print('开始写入文件:' + row['fileName']) 
        newContent = tempContent
        try:
            newContent = newContent.replace('@@表中文名@@', row['tableCnName']).replace('@@表名@@', row['tableName']).replace('@@模''式名@@', row['modeName']).replace('@@文件名@@',row['delFileName'])
            with open(shPath + '\\' + row['fileName'], 'w', encoding='utf-8') as GenShFile:
                GenShFile.write(newContent)
        except Exception as e:
            print('文件写入错误: ' + row['fileName'], e)

if __name__ == "__main__":
    try:
        csvFile = 'D:\\path\\file.csc'
        tempFile = 'D:\\path\\temp.sh'
        shPath = 'D:\\path\\shell' # 这里试了一下,这个文件夹要手动创建,不然上面创建脚本文件时会报错
        tempContent = ''
        with open(tempFile, 'r', encoding='utf-8') as temp:
            tempContent = temp.read()
        csvContent = read_csv(csvFile)
        write_replace_scripte(tempContent, shPath, csvContent)
    except Exception as e:
        print(e)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值