创建命令来写入文件内容

创建命令来写入文件内容

实现此目的最有效的方法是什么?

\begin{filecontents*}{./weekly/week07.tex}
% Week 7
\section{}


\end{filecontents*}
\begin{filecontents*}{./weekly/week08.tex}
% Week 8
\section{}


\end{filecontents*}
\begin{filecontents*}{./weekly/week09.tex}
% Week 9
\section{}


\end{filecontents*}
\begin{filecontents*}{./weekly/week10.tex}
% Week 10
\section{}


\end{filecontents*}
\begin{filecontents*}{./weekly/week11.tex}
% Week 11
\section{}


\end{filecontents*}

平均能量损失

\documentclass[12pt,a4paper]{article}  
\usepackage{filecontents} %% write empty weeklyXX.tex

\begin{document}

\newcommand{\writeweek}[1]{%
\begin{filecontents*}{./weekly/week#1.tex}
% Week #1
\section{}


\end{filecontents*}
}


\writeweek{12}
\writeweek{13}
\writeweek{14}
\writeweek{15}

\end{document}

我遇到了一些错误...

LaTeX Warning: Writing file `././weekly/week12.tex'.

! Missing number, treated as zero.
<to be read again> 
                   \global 
l.18 \writeweek{12}

答案1

filecontents是行verbatim,不能用作另一个命令的参数,也不能用在定义中,因为(在这种情况下)%和在有机会逐字写出\section之前已经以其正常含义被读取了。filecontents

但是,你可以在这里转到较低级别的代码,并使用\detokenize来获得一种逐字处理

\documentclass[12pt,a4paper]{article}  

\newwrite\wks

\begin{document}

{
\catcode`\|=\catcode`\%
\catcode`\%=12 |
\endlinechar=`\^^J |
\gdef\writeweek#1{|
\immediate\openout\wks=./weekly/week#1.tex\relax |
\immediate\write\wks{|
\detokenize{
% Week #1
\section{}

}}|
\immediate\closeout\wks |
}}

\writeweek{12}
\writeweek{13}
\writeweek{14}
\writeweek{15}

\end{document}

这使得文件看起来像


% Week 13
\section {}

相关内容