0

I have a following problem. I need to generate latex using python. I try:

import subprocess


content = """\documentclass{article}
\begin{document}
\thispagestyle{empty}
\hfill  \textbf{\huge Invoice number. 2022-00%(faktura_n)s} \hfill   \\
\end{document}
"""


def main():
    with open('cover.tex','w') as f:
        content = f.read()
        page = content % {'faktura_n' : '27'}
        f.write(page)

    subprocess.call(["pdflatex", "cover.tex"])

if __name__ == "__main__":
    main()

but I got an error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 71, in <module>
  File "<input>", line 63, in main
io.UnsupportedOperation: not readable

How can I insert faktura_n into the content, please? I found this, but it did not help me: Generating pdf-latex with python script

vojtam
  • 1,157
  • 9
  • 34
  • What is `content = f.read()` supposed to mean? You cannot read from a file opened with `'w'`, that's what the exception means. It seems to me that this line is superfluous. – qouify Mar 11 '22 at 09:12
  • You are overwriting `content` variable (the global one with the result from `f.read()`). – Brandt Mar 11 '22 at 09:19

1 Answers1

1

Just remove the line content = f.read() (see my comment) and double the backslashes in your string:

import subprocess

content = """\\documentclass{article}
\\begin{document}
\\thispagestyle{empty}
\\hfill  \\textbf{\\huge Invoice number. 2022-00%(faktura_n)s} \\hfill   \\\\
\\end{document}
"""

def main():
    with open('cover.tex','w') as f:
        page = content % {'faktura_n' : '27'}
        f.write(page)
    subprocess.call(["pdflatex", "cover.tex"])

if __name__ == "__main__":
    main()

or better (credit to @JiříBaum), use an r-string (raw string) to avoid doubling backslashes:

content = r"""\documentclass{article}
\begin{document}
\thispagestyle{empty}
\hfill  \textbf{\huge Invoice number. 2022-00%(faktura_n)s} \hfill   \\
\end{document}
"""
qouify
  • 3,698
  • 2
  • 15
  • 26