开发者

Python: File not formatting like it should

开发者 https://www.devze.com 2023-01-08 09:48 出处:网络
The could below doesnt write to the text file as it should: import re download_results = open(\'download_result.txt\', \'w\')

The could below doesnt write to the text file as it should:

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):
 开发者_如何学C   download_results.write('%s' % (s[i:i+60]))
download_results.write('\n\n')
download_results.close()

The output in the text file is:

AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO

But i would like the output to be:

AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHH
HHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLL
LLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO

Where the script writes "S" in lines containing 60 characters.


Change this:

download_results.write('%s' % (s[i:i+60]))

to this:

download_results.write('%s\n' % (s[i:i+60]))


Then append a newline in your write call within the loop - write() doesn't automatically add a newline, unlike 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()


You aren't writing any newline characters to the file.


Add a newline to the .write invocation. write doesn't add a newline itself (print does, which might have been what confused you)

0

精彩评论

暂无评论...
验证码 换一张
取 消