简体   繁体   中英

for loop to write multiple files as latex output in python

Hey I'm newbie learning python and LaTeX for an economics course and i have query about how to do a for loop to write LaTex ouput in multiple tex files without repeating codes.

result= ['res','res1','res2','res3']
for r in result:
   f = open(r +'.tex', 'w')
   latex= r.summary().as_latex()
   f.write(latex)
   f.close()'

The above code gives an AttributeError: 'str' object has no attribute 'summary' .

The results list contains summary of a regressions that I had run. So each res is a summary of an OLS regression. I want to convert the summary as LATeX code through a for loop instead of writing it like

f = open('res.tex', 'w')
f.write(results.summary().as_latex())
f.close()
f = open('res1.tex', 'w')
f.write(res2.summary().as_latex())
f.close()

and so on... Is there any way to do it through a for loop?

You say "The results list contains summary of a regressions that I had run" however your code

result= ['res','res1','res2','res3']

clearly has result as a list of strings. This gives your error : " AttributeError: 'str' object has no attribute 'summary'."

If you have four variables, then

result = [res, res1, res2, res3]

would give you a list perhaps of your regressions.


It appears you want to walk over a list of results, and a list of filenames.

Something like

result = [res, res1, res2, res3]
filename = ['res', 'res1', 'res2', 'res3']

which you can do like this

for (res, name) in zip(result, filename):
   f = open(name +'.tex', 'w')
   latex= res.summary().as_latex()
   f.write(latex)
   f.close()

or even better

for (res, name) in zip(result, filename):
   with f = open(name +'.tex', 'w')
       latex = res.summary().as_latex()
       f.write(latex)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM