如何阅读.tex文件,并使用python将其内容保存到字符串中?
我在互联网上寻找解决方案,但我找不到任何有用的东西。 我使用的是Windows而不是Linux。
我设法做的是:
f = open("xxx.tex","a")
f.write('This is a test\n')
然而 f 现在是一个对象,而不是一个字符串,如果我是对的。
答案 0 :(得分:3)
你可以这样做:
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=' ')))