Python,字符串分割

4
我有一个大字符串文本文件,我想将每117个字符拆分并放在新行上,然后继续直到文件末尾。
我尝试了以下代码:
``` s = """ 我已经删除了字符串以便更好地显示 """ file = open('testoutput.txt', 'w') while s: output = output + s[:117] + "\n" s = s[117:] file.write(output) file.close() ```
它会将每117个字符分割并放在新行上。
"""
s = s[10:]

文件写入输出内容:

file.write(output) file.close() print "完成"

但是出现了问题,最终输出的文件内容呈级联状态,如下所示:

"this [SHIFT]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations"

T]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



le and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



 descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ts would av[BACKSPACE][BACKSPACE]vary because of mutations



v[BACKSPACE][BACKSPACE]vary because of mutations



E][BACKSPACE]vary because of mutations



CE]vary because of mutations



cause of mutations



utations

`

2个回答

6
while s:
    print s[:117]
    s = s[117:]

3
你可以使用常规的切片语法来切割缓冲区,也可以在读取文件时直接进行拆分。以下是第二种方法的示例:
with open(r"/path/to/some/file") as input_file:
    line = input_file.read(117)
    while line:
        print len(line)
        line = input_file.read(117)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接