2011-02-03 127 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)