将输出打印到单独的文本文件

时间:2018-08-04 04:39:16

标签: python-3.x

下面的脚本打开devices.csv并读取行,然后打印2个字段。我想使用“主机名”字段为每一行创建一个单独的.txt文件,然后将“配置文本”打印到每个文件中。

import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        print(row['Host Name'], row['Configuration Text'])

请协助。

1 个答案:

答案 0 :(得分:0)

import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        with open(os.path.join(path, row['Host Name']), "w") as outfile:     #Create File with host name
            outfile.write(row['Configuration Text'])     #Write Content