python如何从csv打印整行

z9gpfhce  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(199)

如果我打印这个,它会返回两个列表,但我只想它返回两个中的一个我也喜欢它返回一个随机列表,像第一个或第二个,相同的顺序我尝试随机洗牌,选择等,但它返回的只是一个元素,但我想要整个列表我怎么能做到这一点

#the csv file
numbers, one, two, three, four, five
words, nice, please, computer, television, nouse

#the python file
import csv, random
with open("testing.csv", "r", encoding="utf-8") as x:
    c = csv.reader(x)
    for line in c:
        print(line)

这是我尝试的,它返回['numbers','one','two','three','four','five']['words','nice','please','computer','television','nouse']
我只想要这两个中的一个

whitzsjs

whitzsjs1#

你可以用random.choice从一个列表中随机选择一个元素,我们可以把c转换成一个列表,把它变成一个行的列表,然后随机打印其中的一行。

import csv, random
with open("testing.csv", "r", encoding="utf-8") as x:
    c = csv.reader(x)
    lines = list(c)
    print(random.choice(lines))

相关问题