yack yack - 1 year ago 140
LaTeX Question

Adding text into .tex file with python

How can I read .tex file, and save it's content into string using python?

I was searching for the solution on the internet, but I couldn't find anything useful.

I'm using Windows not Linux.

What I managed to do is:

f = open("xxx.tex","a")

f.write('This is a test\n')

However f is a object right now, not a string, if I'm right.

Answer Source

You can do like this:

texdoc = []  # a list of string representing the latex document in python

# read the .tex file, and modify the lines
with open('test.tex') as fin:
    for line in fin:
        texdoc.append(line.replace('width=.5\\textwidth', 'width=.9\\textwidth'))

# write back the new document
with open('test.tex', 'w') as fout:
    for i in range(len(texdoc)):

or like this (could be trickier):

from __future__ import print_function
import fileinput

# inplace=True means that standard output is directed to the input file
for line in fileinput.input('test.tex', inplace=True):
    print(line.replace('width=.5\\textwidth', 'width=.9\\textwidth'), end=' ')))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download