我目前是使用 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]'。有谁知道剥离它并使其 -> 价值?
我尝试以不同的方式将其附加到列表中,但不知道如何“删除它”。
你已经快完成了,只需从列表中取出值即可。
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)