Danxs
Danxs

Reputation: 11

How to save the contents of a for loop in a variable

Hey so i have a program here that reads into a CSV file which i created earlier

import csv
import psycopg2
with open('C:\\Users\\Danis Porovic\\PycharmProjects\\Module1\\berichten.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    for line in csv_reader:
        print(line)

the for loop gives this as a result

['vies', 'Mon 07 Nov 2022 18:43', 'Mia', 'Haarlem']
['vies', 'Mon 07 Nov 2022 18:43', 'Mia', 'Amsterdam']
['vies', 'Mon 07 Nov 2022 18:43', 'Mia', 'Sittard']
['vies', 'Mon 07 Nov 2022 18:43', 'Mia', 'Venlo']
['vies', 'Mon 07 Nov 2022 18:43', 'Mia', 'Helmond']
['Het zou wel wat schoner mogen zijn', 'Tue 08 Nov 2022 00:49', 'Tijmen', 'Hilversum']
['Het zou wel wat schoner mogen zijn', 'Tue 08 Nov 2022 00:49', 'anoniem', 'Roosendaal']

Now how could i save all this information from the for loop in a single variable?

Upvotes: 0

Views: 2032

Answers (1)

Jamie.Sgro
Jamie.Sgro

Reputation: 882

Something like this should do the trick:

result = []
for line in csv_reader:
    result.append(line)

Or using list comprehension:

result = [line for line in csv_reader]

Edit: After comments outlining in more detail what you're looking for. We can transpose the list you usually get so each sublist represents a column from the .csv rather than a row:

import csv
with open('a.csv', 'r') as csv_file:
    regular_list = list(csv.reader(csv_file))
    transposed_result = list(map(list, zip(*regular_list)))
    print(transposed_result)

Shoutout to @Mark Tolonen for removing the for loop iteration and jumping right to csv.reader(csv_file)

Upvotes: 1

Related Questions