<pre><code>with open('pg7163.txt', 'r') as f:
lines = f.readlines()
textfra = '*** START OF THE PROJECT GUTENBERG EBOOK'
texttil = '*** END OF THE PROJECT GUTENBERG EBOOK'
for i, line in enumerate(lines):
if textfra in line:
break
for j, line in enumerate(lines):
if texttil in line:
break
with open("yourfile.txt", "w") as f:
for line in range(len(lines)):
if i < line < j:
f.write(lines)
</code></pre>
<p>我正在尝试导入一个txt文件,并且只写入介于“textfra”和“texttil”之间的文本</p>
<p>要修复<code>TypeError</code>并写入内容,请将最后一段代码更改为:</p>
<pre><code>with open("yourfile.txt", "w") as f:
for k, line in enumerate(lines):
if i < k < j:
f.write(line)
</code></pre>