簡體   English   中英

python 如何從 csv 打印整行

[英]python how to print a whole line from a csv

如果我打印這個,它會返回兩個列表,但我只希望它返回兩個列表中的一個我也喜歡它返回一個隨機列表,如第一個或第二個,我嘗試隨機洗牌,選擇等的相同順序,但它返回一個元素,但我想要整個列表我該怎么做

#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', '電視','鼻子']

我只想要這兩個中的一個

您可以使用random.choice來 select 列表中的隨機元素。 我們可以將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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM