2011-02-03 100 views
4

我有一个大的字符串文本文件,我想分割每117个字符的字符串,并将下一个117个字符放在换行符上,依此类推直到文件结束。Python,分割字符串

我尝试这样做:`S = “” “ 我已删除了可视性原因字符串 ”“” 空间= “” “

”“” 文件=打开( 'testoutput.txt' , 'W') 而S: 打印S [10] 输出=输出+ S + “””

""" 
s = s[10:] 

file.write(输出) file.close() 印刷 “完成” `

,但有该文件的最终输出看起来像这样级联的问题:'此[SHIFT] R后退键分子及其后代将AV,因为突变后退键后退键改变

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 

`

回答

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

damnnn打我吧 – tekknolagi 2011-02-03 04:06:31

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)