[英]Replacing characters in a string loop
我有一个模板txt文件。 该txt文件将被写入10个新文件,但每个文件都会根据任意值列表更改一些字符:
with open('template.txt') as template_file:
template = template_file.readlines()
for i in range(10):
with open('output_%s.txt' % i, 'w') as new_file:
new_file.writelines(template_file)
列表的长度与新文件的数量相同(10)。
我正在尝试将每个新文件第二行的一部分替换为列表中的值。
因此,例如,我想将第2行的每个新文件中的位置[5:16]替换为列表中的相应值。
文件0将具有列表的元素0文件1将具有列表的元素1,依此类推。
我尝试使用replace()
方法:
list = [element0, element1, etc...element9]
for i in template_file:
i.replace(template_file[2][5:16], list_element)
但是它只会用第一个列表元素替换所有文件……不会循环。
任何帮助表示赞赏
我发现有几个问题会阻止您的代码正常工作:
template
,它是行列表,而不是template_file
,这是文件对象 在Python中,字符串是不可变的,这意味着它们无法更改。 replace
函数不会更改字符串,它会返回该字符串的新副本。 此外, replace
会用新文本替换子字符串,无论该子字符串在哪里。 如果要替换特定的索引,建议您自己对字符串进行切片。 例如:
line2 = '0123456789ABCDEFG' element = '-ho-ho-ho-' line2 = line2[:5] + element + line2[16:] # line2 now is '01234-ho-ho-ho-G'
请不要使用list
作为变量名。 它是一种类型,可用于构造新列表,如下所示:
empty = list() # ==> [] letters = list('abc') # ==> ['a', 'b', 'c']
表达式template_file[2][5:16]
不正确:首先,它应该是template
,而不是template_file
。 第二,第二行应该是template[1]
,而不是template[2]
因为Python列表是从零开始的
list_element
变量未在代码中声明 话虽如此,我发现将模板文件构造为带有占位符的真实模板更加容易。 我稍后再说。 如果您仍然坚持用某些东西替换第2行的索引5-16,这是我测试过的一种解决方案,它可以工作:
with open('template.txt') as template_file:
template = template_file.readlines()
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
line2 = template[1]
line2 = line2[:5] + element + line2[16:]
for line_number, line in enumerate(template, 1):
if line_number == 2:
line = line2
out_file.write(line)
笔记
如果您可以控制模板文件,建议您使用string.Template
类使搜索和替换更加容易。 由于我不知道您的模板文件是什么样子,因此我将组成自己的模板文件:
line #1
This is my ${token} to be replaced
line #3
line #4
请注意,我打算将${token}
替换${token}
代码中的元素之一。 现在看代码:
import string
with open('template.txt') as template_file:
template = string.Template(template_file.read())
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
out_file.write(template.substitute(token=element))
笔记
template_file.read()
一次读取了整个文件。 如果模板文件很大,这可能是一个问题,但是以前的解决方案也遇到了与此相同的性能问题 string.Template
类使搜索/替换更容易 substitute(token=element)
对此表示:替换所有$token
或${token}
的情况下, template
与element
。 如果模板文件太大而无法一次放入内存,则可以修改第一个解决方案以逐行读取它,而不是一次读取所有行。 我不会在这里提出这个解决方案,只是一个建议。
看起来你需要
list = [element0, element1, etc...element9]
for i in list:
template_file = template_file.replace(template_file[2][5:16], i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.