问题描述
下面的可能不会将其写入文本文件:
import re
download_results = open('download_result.txt', 'w')
s = 'AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGG##GGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMM&&MMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO'
s = re.sub(r'[^\w]','',s)
s = ''.join(s)
for i in range(0, len(s), 60):
download_results.write('%s' % (s[i:i+60]))
download_results.write('\n\n')
download_results.close()
文本文件中的输出为:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
但我希望输出是:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHH
HHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLL
LLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
脚本在包含60个字符的行中写“ S”。
1楼
更改此:
download_results.write('%s' % (s[i:i+60]))
对此:
download_results.write('%s\n' % (s[i:i+60]))
2楼
然后在循环中的write
调用中添加换行符-write write()
不会自动添加换行符,这与print
不同。
for i in range(0, len(s), 60):
download_results.write('%s\n' % (s[i:i+60]))
download_results.write('\n')
download_results.close()
3楼
您没有在文件中写入任何换行符。
4楼
在.write
调用中添加换行符。
write
本身不会添加换行符( print
会添加换行符,这可能会使您感到困惑)