0

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'.

2
  • If each line of your .csv holds only one value, there's no need for a .csv! Just read it as a basic textfile.
    – Swifty
    Commented Jul 7 at 9:02
  • But will it still read the different values as different, or will it group them together as one text? Commented Jul 9 at 23:36

3 Answers 3

2

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

You are almost there, Just need to take out the value from the list.

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

If greetings.csv only contains one value per line, no need to consider it as a csv! A simple readlines will do:

with open("greetings.csv") as f:
    CSVars = [line.strip() for line in f.readlines()]

Not the answer you're looking for? Browse other questions tagged or ask your own question.