Learning Python: Is there a better way to write words + vars to file?
For example, the following code:
#!/usr/bin/env python
cliente = 'TESTE'
servidor_virtual = '10.2.192.115'
porta = '22'
conf = "# pool " + cliente + '\n' "virtual_server" + servidor_virtual + porta + '\n'
f = open('cliente.conf', 'w')
f.write(conf)
f.close()
I'm beginning at Python and creating a model to write some confs to a file. I just found this way, but i want to know if there another more elegant way to do this. And i want to mix word 开发者_运维知识库with variables values too.
To process configuration files you should use the ConfigParser
module. See the ConfigParser docs.
Another possible way to do this is to use lists and the string join function.
conf = ["# pool ", cliente, '\n', "virtual_server", servidor_virtual, porta, '\n']
f.write(''.join(conf))
Do this.
cliente.py
cliente = 'TESTE'
servidor_virtual = '10.2.192.115'
porta = '22'
Actual Application.py
conf= {}
execfile( 'cliente.py', conf )
# now conf['cliente'], conf['servidor_virtual'] and conf['porta'] are all set.
The only thing I might suggest is to use string formatting. I think it's generally faster than string concatenation, but can be more difficult to read. In your case,
conf = "# pool %s\nvirtual_server %s:%d\n" % (cliente,servidor_virtual,porta)
Note that I cleaned up the string a little - you have "virtual_server" followed by the IP address with no space or separator at all, and then the port is directly after that with no separator.
Other than that, what you have is fine.
精彩评论