简体   繁体   English

在python中将CSV解析为模板

[英]Parsing CSV to template in python

I want to write simple python script which will first load .csv file and then output it to another file using provided template:我想编写简单的 python 脚本,它首先加载 .csv 文件,然后使用提供的模板将其输出到另一个文件:

FirstVariable Cleartext-Password := "SecondVariable", Service-Type := Framed-User
    Framed-IP-Address := ThirdVariable,
    MS-Primary-DNS-Server := 8.8.8.8,
    Fall-Through = Yes,
    Mikrotik-Rate-Limit = 4thVariableM/5thVariableM

example:例子:

input file:输入文件:

john;lovelycat;192.168.1.1;40;30

output:输出:

john Cleartext-Password := "lovelycat", Service-Type := Framed-User
    Framed-IP-Address := 192.168.1.1,
    MS-Primary-DNS-Server := 8.8.8.8,
    Fall-Through = Yes,
    Mikrotik-Rate-Limit = 40M/30M

Other parameters above should stay as they are, i only need to paste the mentioned values.上面的其他参数应该保持原样,我只需要粘贴提到的值。

At this moment i know only how to read and write files, but i have no clue how to tell python to output text to file and how to use variables in the text so i can save the parameters from .csv to variables and then output it.目前我只知道如何读取和写入文件,但我不知道如何告诉 python 将文本输出到文件以及如何使用文本中的变量,以便我可以将 .csv 中的参数保存到变量中,然后将其输出.

Could you please help me with tips how can i accomplish it?你能帮我提供一些提示,我该如何完成它?

Using csv module with f-string使用带有f-string csv模块

Ex:前任:

import csv


with open(filename) as infile:
    reader = csv.reader(infile, delimiter=";")
    for row in reader:
        template_data = f"""{row[0]} Cleartext-Password := "{row[1]}", Service-Type := Framed-User
                    Framed-IP-Address := {row[2]},
                    MS-Primary-DNS-Server := 8.8.8.8,
                    Fall-Through = Yes,
                    Mikrotik-Rate-Limit = {row[3]}M/{row[4]}M"""
        print(template_data)

Output:输出:

john Cleartext-Password := "lovelycat", Service-Type := Framed-User
                    Framed-IP-Address := 192.168.1.1,
                    MS-Primary-DNS-Server := 8.8.8.8,
                    Fall-Through = Yes,
                    Mikrotik-Rate-Limit = 40M/30M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM