用python代码,列表格式的文本文件,我们想转换为hcl格式的terraform。用expected格式,它无法添加双引号“”与列表。
下面是列表文件input.txt
spn-owner-adm = owner, reader, admin, net-admin, str-admin, viewer
spn-net-adm = admin, net-admin, str-admin
spn-str-adm = str-admin, viewer, compute-admin, viewer, reader
spn-my-adm = owner, admin, viewer, reader
预期输出. txt
spn-owner-adm = [ "owner", "reader", "admin", "net-admin", "str-admin", "viewer" ]
spn-net-adm = [ "admin", "net-admin", "str-admin" ]
spn-str-adm = [ "str-admin", "viewer", "compute-admin", "viewer", "reader" ]
spn-my-adm = [ "owner", "admin", "viewer", reader" ]
output.txt文件错误,每个字符用双引号引起来。
spn-owner-adm = [" ""o""w""n""e""r"","" ""r""e""a""d""e""r"","" ""a""d""m""i""n"","" ""n""e""t""-""a""d""m""i""n"","" ""s""t""r""-""a""d""m""i""n"","" ""v""i""e""w""e""r" ]
spn-net-adm = [" ""a""d""m""i""n"","" ""n""e""t""-""a""d""m""i""n"","" ""s""t""r""-""a""d""m""i""n" ]
spn-str-adm = [" "" ""s""t""r""-""a""d""m""i""n"","" ""v""i""e""w""e""r"","" ""c""o""m""p""u""t""e""-""a""d""m""i""n"","" ""v""i""e""w""e""r"","" ""r""e""a""d""e""r" ]
spn-my-adm = [" ""o""w""n""e""r"","" ""a""d""m""i""n"","" ""v""i""e""w""e""r"","" ""r""e""a""d""e""r" ]
#!/usr/bin/env python3
import re
myspn_pattn = r"""^spn-.*-adm.*$"""
spnup = []
myfile = "input.txt"
with open(myfile, 'r') as fsp, open('output.txt', 'w+') as fspn:
fspn.write("spn = {" "\n\n")
for myspn in fsp:
spnmatch = re.findall(myspn_pattn, myspn)
if spnmatch:
for line in spnmatch:
spnname = line.split('=')[0]
spnrglist = line.split('=')[1]
#print("\t" '{} = "{}",' .format(spnname, spnrglist))
spnup = '{} = [{} ]\n'.format(spnname, ''.join(['{}'.format(v) for v in spnrglist]))
fspn.write(spnup)
fspn.write("\n")
fspn.write("\t" "}")
1条答案
按热度按时间wfypjpf41#
由于
sprnglist
是一个字符串,执行for v in sprnglist
会遍历字符。话虽如此,我无法复制您描述的每个字符都有引号的问题,但代码示例的输出无论如何都不是预期的结果。如果你想得到想要的输出,你首先需要将字符串分割成你想要的部分(每个部分都用
,
分割),然后用引号括起来,然后重新连接它。在下面的例子中,我用,
连接它以用于输出格式。我还想指出的是,使用
fspn.write("\t" "}")
会导致输出中出现奇怪的缩进。output.txt: