【数据处理_Python】使用python脚本将模板文件修改内容后重命名另存为新文件

示例代码说明:

读取一份模板conf文件,将里面的指定字段替换为新字段,并将修改后的conf文件以新字段重命名另存为新文件。模板conf文件换行符设置为Unix(LF),重新写入的conf文件换行符需要保持一致。

import os
# 要替换的字段
old_string = "sampletable"
# 样本文件
input_conf = r'D:\sample\sample.conf'
#修改文件后输出路径
output_dir ='D:/sampleout'
#读取替换字段文件路径
input_dir = r'D:\HQ\input'
with open(input_conf, 'r',newline='\n') as infile:
    content = infile.read()
    for filename in os.listdir(input_dir):
      if filename.endswith('.csv'):
         nameparts = filename.split('.')
         new_string = nameparts[0]
         # 执行替换操作
         new_content = content.replace(old_string, new_string)
         # 写入新文件
         output_file_path = os.path.join(output_dir, new_string+'.conf')
         with open(output_file_path, 'w',newline='\n') as oufile:
             oufile.write(new_content)
         oufile.close()
infile.close()

示例结果输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌小丹Fighting

喜欢就给我加蛋

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值