首页 > 解决方案 > 在文件的每一行上创建一个新文件名

问题描述

我可以打开文件“setup.conf”,将文本从“Hostname=server”替换为“Hostname=server2”并将其保存为“setup2.conf”。

但是,我希望“list.txt”中的每一行都成为新文件的名称,而不是“setup2.conf”。

“list.txt”的内容:

server1
server2
server3

例如,我为阅读每一行所做的事情:

fh = open('list.txt')
while True:
    line = fh.readline()
    print(line)
    if not line:
        break
fh.close()

我为替换文本和保存文件所做的示例:

fin = open("setup.conf", "rt")
fout = open("setup2.conf", "wt")

for line in fin:
    fout.write(line.replace('Hostname=server1', 'Hostname=server2'))

fin.close()
fout.close()

标签: python

解决方案


为每个读取行打开一个新文件,然后写入它。例如

with open('list.txt') as fh:
    for line in fh:
        server = line.rstrip()
        with open(server + ".conf", "w") as fout, open("setup.conf") as setup:
            for line in setup:
                fout.write(line.replace("Hostname=server1", "Hostname=" + server)
                fout.write("\n") 

推荐阅读