2015-12-21 48 views
3

我想將一個非常大的.txt文件分割成相等的部分文件,每個部分包含N行。並將其保存到一個文件夾將一個txt文件分成N行?

with open('eg.txt', 'r') as T: 
    while True: 
     next_n_lines = islice(T, 300) 
     f = open("split" + str(x.pop()) + ".txt", "w") 
     f.write(str(next_n_lines)) 
     f.close() 

但這創建了數據

" < itertools.islice object at 0x7f8fa94a4940 >" 
txt文件

一個文件。

我想保持相同的結構和風格保持在原來的txt文件。

,當它到達文件末尾,以及該代碼不會自動終止。如果可能的話,我會讓代碼停止寫入文件並退出,如果 沒有數據可寫。

回答

3

您可以使用iterislice,用枚舉給你的文件唯一的名稱取n行的時間。 f.writelines將每條線路列表寫入新文件:

with open('eg.txt') as T: 
    for i, sli in enumerate(iter(lambda:list(islice(T, 300)), []), 1): 
     with open("split_{}.txt".format(i), "w") as f: 
      f.writelines(sli) 

你的代碼循環永遠爲你不包含任何破發狀態,使用iter對空列表將意味着循環結束時,迭代器已經耗盡。

此外,如果你想通過一個islice對象寫出來,你可以在它上面調用writelines,即f.writelines(next_n_lines),str(next_n_lines)

+0

對於任何人發現這幾年下來,你需要把這個上面的代碼。 https://docs.python.org/3/library/itertools.html#itertools.islice –

2

問題是達itertools.islice返回迭代和你正在寫它在你的文件str這是在Python中的函數表示(顯示對象的身份):

< itertools.islice object at 0x7f8fa94a4940 > 

至於更pythinic方式切片一個迭代器相等的部分,您可以使用下面grouper功能,它已建議由蟒蛇維基爲itertools recipes

def grouper(iterable, n, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue) 

你可以通過你的文件對象作爲iterato R鍵對結果的功能,然後循環,並將其令狀文件:

with open('eg.txt', 'r') as T: 
    for partition in grouper(T,300): 
     # do anything with `partition` like join the lines 
     # or any modification you like. Then write it in output. 
相關問題