假设文本文件是这样的:
1
2
3
4
5
6
...
我想要的是以N行的方式对内容进行randomely排序,而不是对每组中的行进行洗牌,如下所示:
#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
有更简单的方法吗?
答案 0 :(得分: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))