擅长:python、mysql、java
<p>优化方式:</p>
<pre><code>import os
def get_file(idx):
''' Opens file in write mode using `idx` arg as filename suffix.
Returns the file object created
'''
fn = 'filename{}.txt'.format(idx)
return open(fn, 'w')
with open(os.path.normpath('C:\\Users\\abc.txt'), 'r') as f:
idx = 1
out_file = get_file(idx)
for l in f:
if not l.strip():
out_file.close()
idx += 1
out_file = get_file(idx)
else:
out_file.write(l)
</code></pre>