简体   繁体   English

使用python将文本添加到.tex文件中

[英]Adding text into .tex file with python

How can I read .tex file, and save it's content into string using python? 如何读取.tex文件,并使用python将其内容保存到字符串中?

I was searching for the solution on the internet, but I couldn't find anything useful. 我在互联网上寻找解决方案,但找不到任何有用的方法。
I'm using Windows not Linux. 我使用的是Windows,而不是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. 但是,如果我是对的, f现在是一个对象,而不是字符串。

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)):
        fout.write(texdoc[i])

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=' ')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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