<p>1:通过使用<a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">^{<cd1>}</a>将单个字符串转换为字符串列表,可以消除临时文件。这样做的副作用是从每一行中删除<code>\n</code>,您必须在后面添加或说明这些内容。你知道吗</p>
<pre><code>tempContent = dataConverted.split('\n')
</code></pre>
<p>2:有两种方法可以解决这个问题。首先是简单地使用<code>else</code>来编写您之前跳过的行。(如果使用上面的<code>split</code>提示,则不需要<code>rstrip</code>)。你知道吗</p>
<pre><code>if '|' in line:
f.write('|' + line + '| \n')
else:
f.write(line + '\n')
</code></pre>
<p>另一种方法是,如果行需要更新,则更新它,然后在任何情况下都写入它。你知道吗</p>
<pre><code>if '|' in line:
line = '|' + line + '| '
f.write(line + '\n')
</code></pre>
<p>3:这更难,因为你不只是想把这些条添加到一个空白行之后的任何一行,你想检测到有一个表出现了。这意味着你需要向前看。这里有一个小功能,你可以用它来自动看前面。你知道吗</p>
<pre><code>def lookahead(seq):
current = None
for upcoming in seq:
if current is not None:
yield current, upcoming
current = upcoming
if current is not None:
yield current, None
</code></pre>
<p>你可以这样使用它:</p>
<pre><code>for line, upcoming in lookahead(tempContent):
if (upcoming and '|' in upcoming) or ('|' in line):
line = '|' + line + '|'
</code></pre>