python根据模板文件批量创建文件脚本

2024-10-09 08:27:25 浏览数 (4)

1.模板文件.txt

欢迎访问这座城市:德州 行政区域编号:371400 根据高德地图(https://lbs.amap.com/tools/picker)查询经纬度查询: jingdu,weidu BYE-BYE

2.python代码

代码语言:javascript复制
import shutil
import os

params = [
    ["德阳","510600","104.404417","31.133116"],
    ["阿尔山","152202","119.950654","47.183053"]
]

##文件创建的目前同python文件的目录
for d in params:
    file = '模板创建文件-' d[0] '.txt'
    shutil.copyfile('模板文件.txt', file)
    if os.path.exists('模板创建文件-' d[0] '.txt'):
        print(file '文件复制成功!')

    file_data = ''

    with open(file, 'r',encoding='utf-8') as f:
      for line in f.readlines():
        line = line.strip()
        if '371400' in line:
            line = line.replace('371400', d[1])
        if '德州' in line:
            line = line.replace('德州', d[0])
        if 'jingdu' in line:
            line = line.replace('jingdu', d[2])
        if 'weidu' in line:
            line = line.replace('weidu', d[3])
        print(line)
        #file_data  = line   'n'
        file_data  = line   'r'
        #file_data  = line   'rn'  ## 这样的话是换了两行。
    with open(file, "w", encoding="utf-8") as f:
        f.write(file_data)
        print(file '文件创建成功!')

3.生成后的文件

0 人点赞