2017-10-15 21 views
1

假設文本文件是這樣的:如何洗牌文本文件的內容中的n行集團在Python

1 
2 
3 
4 
5 
6 
... 

我想是randomely訂購內容的N行基非在每組中排序如下:

#In this case, N = 2. 
5 
6 
1 
2 
7 
8 
... 

我的文件不是很大,肯定會小於50行。

我試圖做到這一點使用此代碼:

import random 


with open("data.txt", "r") as file: 
    lines = [] 
    groups = [] 
    for line in file: 
     lines.append(line[:-1]) 
     if len(lines) > 3: 
      groups.append(lines) 


      lines = [] 

    random.shuffle(groups) 


with open("data.txt", "w") as file: 
    file.write("\n".join(groups)) 

但我得到這個錯誤:

Traceback (most recent call last): 
    File "C:/PYTHON/python/Data.py", line 19, in <module> 
    file.write("\n".join(groups)) 
TypeError: sequence item 0: expected str instance, list found 

是否有這樣做的一個簡單的方法?

回答

4

您試圖加入列表清單;首先將它們弄平:

with open("data.txt", "w") as file: 
    file.write("\n".join(['\n'.join(g) for g in groups])) 

您可以使用recommended methods of chunking中的任何一個來生成組。隨着file對象,所有你需要做的是zip()與自身的文件:

with open("data.txt", "r") as file: 
    groups = list(zip(file, file)) 

注意,如果有奇數號文件中的行的這個會下降的最後一行。這包括現在的換行符,所以加入''而不是'\n'

你也可以洗牌之前一起加入兩行的每個組:

with open("data.txt", "r") as file: 
    groups = [a + b for a, b in zip(file, file)] 

random.shuffle(groups) 

with open("data.txt", "w") as file: 
    file.write("".join(groups)) 
+0

感謝。有沒有辦法只打開一次文件? – user1236969

+0

@ user1236969:sure:[在寫入文件之前刪除文件的內容(使用Python)?](// stackoverflow.com/q/41915140);在「r +」模式下打開,讀取,倒帶,截斷,然後寫入。 –