我有一个格式为三列的文本文件:
1 10045 0.120559958
1 157465 0.590642951
2 222471 0.947959795
2 222473 0.083341617
3 222541 0.054014337
3 222588 0.060296547
4 237571 0.646742879
这是我的代码,它以上面显示的三列格式打印我的文件:
import csv
import random
import os.path
def filename ():
filename = 'filename.txt'
with open ("filename.txt", "r") as data_file:
for line in data_file.readlines():
line = line.strip().split()
print (line [0], line [1], line[2])
如何更改我的代码,使其以随机顺序打印三列的行?我想要的输出是例如:
2 222473 0.083341617
4 237571 0.646742879
3 222588 0.060296547
1 10045 0.120559958
1 157465 0.590642951
2 222471 0.947959795
3 222541 0.054014337
更新: 我已经成功地随机打印了我的文件。但是,我该如何去除每行之间多余的空格?
2 202174949 0.029547574
5 211764876 0.605756554
3 188664399 0.209919535
2 219396633 0.271415602
8 152970529 0.371399522
2 86250214 0.765947161
2 51751412 0.382815804
6 93732369 0.230918546
我试过使用:
splitted_line = line.strip("\n").split(";")
但是我的输出没有变化。额外的空格仍然存在。
请您参考如下方法:
您可以只将文件的行读入列表并调用 random.shuffle在上面。然后打印这些行。
import random
with open('filename.txt', 'r') as fin:
lines = list(fin)
random.shuffle(lines)
for line in lines:
print line, # the trailing comma suppresses the newline since the line already has that.
为了兼容python2 -> python3,可以使用print函数
from __future__ import print_function
# ...
for line in lines:
print(line, end='')
