python - 在文件的每一行上创建一个新文件名
问题描述
我可以打开文件“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()
解决方案
为每个读取行打开一个新文件,然后写入它。例如
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")
推荐阅读
- c - 只有在循环结束时再次对字符串进行 malloc 时,fgets 循环才能正常工作
- java - 在同一服务器上创建 IBM MQ 连接的最佳方式
- javascript - 如何在 Angular 项目中使用 .flat()?
- java - Elastic Transcoder 输出持续时间与我的输入持续时间的总和不匹配
- python - 连接两个数据框并扩展其中一个的内容
- css - CSS 如何连接线
- c# - Unity - scale UI element based on closeness to a target?
- r - 根据每行中的缺失值选择列
- python - Why is etree returning nothing from my SVG when I run `for glyph in font.iter('glyph')`?
- angular-material - 角材料单选按钮组 - 屏幕阅读器无法正确阅读