Python 如何在文本前加上前缀,写入TXT中每一行的开头,并以额外的一行结束
我有一个文本文件,如下所示:Python 如何在文本前加上前缀,写入TXT中每一行的开头,并以额外的一行结束,python,python-2.7,file-io,Python,Python 2.7,File Io,我有一个文本文件,如下所示: this is 1 line this is 2 line this is 3 line 我想将其转换为如下内容: \begin{enumerate} \item this is 1 line \item this is 2 line \item this is 3 line \end{enumerate} 我使用的代码如下: prefix = '\\item ' with open('new.txt', 'r') as src: with open(
this is 1 line
this is 2 line
this is 3 line
我想将其转换为如下内容:
\begin{enumerate}
\item this is 1 line
\item this is 2 line
\item this is 3 line
\end{enumerate}
我使用的代码如下:
prefix = '\\item '
with open('new.txt', 'r') as src:
with open('dest.txt', 'w') as dest:
dest.write("\\begin{enumerate}\n")
for line in src:
dest.write('%s%s\n' % (prefix, line.rstrip('\n')))
参考:
但我似乎无法正确添加最后一行“\end{enumerate}”。有人能帮忙吗?只需在
with
子句末尾添加这一行:
prefix = '\\item '
with open('new.txt', 'r') as src:
with open('dest.txt', 'w') as dest:
dest.write("\\begin{enumerate}\n")
for line in src:
dest.write('%s%s\n' % (prefix, line.rstrip('\n')))
dest.write("\\end{enumerate}\n")