0

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]

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

Format seems right, is there an easy way of assigning each line to a different variable? I want the datetimes to be variable x and integer values to be variable y, both variables in list format.
Can you try x, y = tuple(csv.reader(f, delimiter=","))? I'm not 100% sure if the tuple constructor will take the reader but I think it will.
Thank you, it works, i have tried about 5 different solutions to the same 3 lines of code, none of them worked exactly like i wanted it.
@LasseFisker Added this part to the question, if your question was solved please mark this answer as the solution so that the question gets marked as solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.