[英]Adding text into .tex file with python
如何讀取.tex文件,並使用python將其內容保存到字符串中?
我在互聯網上尋找解決方案,但找不到任何有用的方法。
我使用的是Windows,而不是Linux。
我設法做到的是:
f = open("xxx.tex","a")
f.write('This is a test\n')
但是,如果我是對的, f現在是一個對象,而不是字符串。
您可以這樣:
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])
或這樣(可能更棘手):
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.