擅长:python、mysql、java
<p>首先收集所有的输入,然后用<code>.join()</code>一次写入</p>
<pre><code>text = []
user = input('Enter text to write to file (\'quit\') to end: ')
text.append(user)
while user != 'quit':
user = input('Enter text to write to file (\'quit\') to end: ')
text.append(user)
res = '\n'.join(text)
with open('text.txt', 'w') as f:
f.write(res)
</code></pre>
<blockquote>
<pre><code>Enter text to write to file ('quit') to end: vash
Enter text to write to file ('quit') to end: the
Enter text to write to file ('quit') to end: stampede
Enter text to write to file ('quit') to end: quit
chrx@chrx:~/python/stackoverflow/10.11$ cat text.txt
vash
the
stampede
</code></pre>
</blockquote>