擅长:python、mysql、java
<p>你的问题是:</p>
<pre><code>for topic,words in topics_words:
# print(" ".join(words).encode('utf-8'))
# print(words)
f = open(str(i)+'.txt', 'wb')
f.write(" ".join(words).encode('utf-8'))
# f.write(words.encode('utf-8'))
f.close()
</code></pre>
<p>在完成循环后,您将关闭该文件,因此它只保存最后一个文件。更改为:</p>
<pre><code>for topic,words in topics_words:
# print(" ".join(words).encode('utf-8'))
# print(words)
# f = open(str(i)+'.txt', 'wb')
with open(str(i) + '.txt', 'wb') as f:
f.write(" ".join(words).encode('utf-8'))
# f.write(words.encode('utf-8'))
# f.close()
</code></pre>
<p>用“with语句”打开文件会在文件写入后自动关闭它。你知道吗</p>
<p>另外,文件名“str(i)+'.txt'”中的“i”来自哪里?如果它来自外部的“for循环”,则应将其作为参数添加到函数中。不要将其用作全局变量。你知道吗</p>