工作需要,这前两天写了一个简单的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)