vendredi 17 avril 2020

Best practice to write file in python

I'm developing a files exchange protocol software in python. For obvious reason I need to write a lot of similar file. At the moment what I'm doing is open a file and write hard coded instruction as the following:

with open(file, 'w') as f:
    f.write('do instruction param1, param2;')

What I'm thinking to do it's to create some .txt file as template, in order to avoid redundancies and hard coded parameters. And also if parameters are default I can made a cp instead of read, and write again.

with open(template, 'r') as temp_file:
     content = temp_file.read()
with open(file, 'w') as f:
     f.write(content.format(param1, param2))

I'm wondering if is a good pattern and if there is a more elegant and "Pythonic" way to do this.

Aucun commentaire:

Enregistrer un commentaire