![]() |
Writing many variables to a file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Writing many variables to a file (/thread-1376.html) |
Writing many variables to a file - birdieman - Dec-28-2016 I am still a beginner to Python and have the following code to write about 14 variables to a file: f.write('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}\n'.format ################### WRITE THE TAXABLE CATEGORY (year, yourage, herage, round(begintaxableequity), round(endtaxableequity), round(begintaxablefixedincome), round(fixedincome), round(endtaxablefixedincome), round(begintaxablecash), round(cashincome), round(endtaxablecash), round(totaltaxableassets), round(totaltaxabledivincome), taxableequitygwth, taxablefixedincomediv, taxablecashdiv))Everything works fine -- no problems. My questions: 1. If I have say 100 variables, do I follow the same logic/pattern? 2. Is there a better/faster/simpler way to write many variables? thanks RE: Writing many variables to a file - j.crater - Dec-28-2016 1. You may follow same pattern to complete your task 2. I think a better/faster/simpler way is to have your variables stored in a container (e.g. a list or tuple - which, in a way, you have actually done in "format" already) and loop over that list, each iteration being a write to file The latter option will also make it a bit easier (and definitely more readable and less error prone) to add/remove variables if needed. RE: Writing many variables to a file - wavic - Dec-28-2016 Hello! You have many repeating tasks. Make a function pass the original values as parameters or list of parameters and return the rounded values as list. Make a list with all you want and save it as a CSV file. Consider to shorten all the variables names. It's easy to misspell them. RE: Writing many variables to a file - Ofnuts - Dec-30-2016 (Dec-28-2016, 10:09 PM)birdieman Wrote: Everything works fine -- no problems. My questions: If you have 100 variables the problem is keeping track of the 100 variables throughout the code, not just at the place where you print them... What I would so is see if I can find logical groupings of these variables and make object classes from them. Then I can define/code the __str__(self) method in these classes and I just have to give the class instance in a print call and it would output the string with all its components... And these classes will likely have other profitable uses. |