pythonlistcsvread-csv

Reading CSV Files And Stripping Values


I am currently new with coding in Python with CSV files, and need help with the following code:

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))

Basically, in this code, I get a random value from a file called 'greeting.csv'. However, whenever I get a value, it is always in this format -> '[value]'. Does anyone know to strip it and make it -> value?

I tried to append it to a list in different ways, but do not know how to 'strip it'.


Solution

  • Each iteration of reader returns a list. It does this because it's assumed that your CSV file has multiple columns per row. Each element of the list would represent a column value.

    So, without limiting your list to a certain number of rows (not a good idea as you may not have as many rows in the CSV as you had hoped):

    import csv
    import random
    
    with open("greetings.csv", "r", newline="") as f:
        reader = csv.reader(f)
        lst = [e[0] for e in reader]
        print(random.choice(lst))
    

    ...alternatively...

    import csv
    import random
    
    with open("greetings.csv", "r", newline="") as f:
        reader = csv.reader(f)
        lst = list(reader)
        print(*random.choice(lst))