读取 CSV 文件并剥离值

问题描述 投票:0回答:1

我目前是使用 CSV 文件进行 Python 编码的新手,需要有关以下代码的帮助:

import csv
import random

# Initialize an empty list to store the CSV variables
CSVars = []

# Read the CSV file
with open('greeting.csv', 'r') as f:
    reader = csv.reader(f)
    for _ in range(16):  # Assuming there are 16 rows in the CSV
        CSVars.append(next(reader))
    print(random.choice(CSVars))

基本上,在这段代码中,我从名为“greeting.csv”的文件中获取一个随机值。但是,每当我获得一个值时,它总是采用这种格式 -> '[value]'。有谁知道剥离它并使其 -> 价值?

我尝试以不同的方式将其附加到列表中,但不知道如何“删除它”。

python list csv read-csv
1个回答
1
投票

你已经快完成了,只需从列表中取出值即可。

import csv
import random

CSVars = []

# Read the CSV file
with open('greeting.csv', 'r') as f:
    reader = csv.reader(f)
    for _ in range(16):  # Assuming there are 16 rows in the CSV
        # NOTE: You need to take the first value from the next(reader) because it 
         #is giving you a list.
        CSVars.append(next(reader)[0]) 
    print(random.choice(CSVars))

print(CSVars)
© www.soinside.com 2019 - 2024. All rights reserved.