当前位置: 代码迷 >> python >> Python:文件格式不正确
  详细解决方案

Python:文件格式不正确

热度:64   发布时间:2023-06-13 13:31:41.0

下面的可能不会将其写入文本文件:

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”。

更改此:

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

对此:

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

然后在循环中的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()

您没有在文件中写入任何换行符。

.write调用中添加换行符。 write本身不会添加换行符( print会添加换行符,这可能会使您感到困惑)