1

I have a .csv file in which data is separated by commas and I want to separate it into columns. For this, I am trying to put every row element in a list and then put them into columns in a new file. The code I'm using is the following:

import csv

c1 = []
c2 = []
c3 = []
with open('File.csv', 'r') as f:
   reader = csv.reader(f, delimiter=',')
   for row in reader:
       c1.append(row[0])
       c1.append(row[1])
       c1.append(row[2])

For some reason, I am able to store in c1 just the column of the .csv file. For c2 and c3 I'm getting an error. It seems like "reader" jumps into the next row right after getting the first element of the current row. Could somebody give me an idea? Perhaps there is even an easier way to do it?

3
  • stackoverflow.com/questions/19486369/… Commented Nov 1, 2019 at 13:43
  • 1
    can use pandas to do what it is i think you are looking to do Commented Nov 1, 2019 at 13:43
  • Thanks Nathan, but it doesn't work for my .csv file. The file I'm using has around 380 rows. Somehow when I use Pandas I get the following error message: pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 6, saw 9. That's why I started to look for another method. In my case, the only thing I have as starting point is this .csv file. No previous list. Commented Nov 1, 2019 at 14:05

1 Answer 1

0

There's a syntactical error there. You are appending everything in c1 instead of putting values in various lists.

Assumption [big one!] - csv file only consists of 3 columns per row.

I tested it with following code

import csv

c1 = []
c2 = []
c3 = []
with open('csvfile.csv', 'r') as f:
   reader = csv.reader(f, delimiter=',')
   for row in reader:
       c1.append(row[0])
       c2.append(row[1])
       c3.append(row[2])
print(f'column1:{c1}')
print(f'column2:{c2}')
print(f'column3:{c3}')

Output

% python3 csv_to_column.py
column1:['1', '4', '7']
column2:['2', '5', '8']
column3:['3', '6', '9']

Reference - dummy csv file

% cat csvfile.csv
1,2,3
4,5,6
7,8,9
Sign up to request clarification or add additional context in comments.

Comments

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.