Lasse Fisker
Lasse Fisker

Reputation: 21

Python reading csv files, assign each line to a variable

Currently i have problems with the formatting of the read data. Instead of returning a list for each row, the code returns a list with each index being a column.

The csv file looks like this:

2020-08-26 00:00:00,2020-08-27 00:00:00,2020-08-28 00:00:00 
1505,1515,1527

And the code is this:

    with open("csvfile.csv", "r") as f:
        reader = csv.reader(f, delimiter=",")
        for i, line in enumerate(reader):
            print(line[0].format(i, line))

Current output:

2020-08-26 00:00:00
1505

Desired output:

['2020-08-26 00:00:00','2020-08-27 00:00:00','2020-08-28 00:00:00'] 
[1505, 1515, 1527]

Upvotes: 0

Views: 1514

Answers (1)

Adirio
Adirio

Reputation: 5286

Try this:

import csv

with open("csvfile.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")
    for line in reader:
        print(line)

We could even make it a one-liner:

import csv

with open("csvfile.csv", "r") as f:
    [print(line) for line in csv.reader(f, delimiter=",")]

And if you just have these 2 lines and want each of them in a variable you can use:

import csv

with open("csvfile.csv", "r") as f:
    x, y = tuple(csv.reader(f, delimiter=","))
# Use x and y, preferably outside of the `with` statement
# as we can already close the file

Upvotes: 3

Related Questions