2

If I use the following code:

with open('examplefile.csv') as tst:
    for line in tst:
        x = line
        print(x)

I see 5 columns and numerous rows.

How do I take one row at a time and set variables to each item in a row?

iled
  • 2,142
  • 3
  • 31
  • 43
Mim
  • 29
  • 2

2 Answers2

4

The for loop already takes one line at a time

Split the line into a list.

Assuming comma is the delimiter, this assigns variables to each column

x, y, z, a, b = line.split(',')
print(x)

This also assumes you don't have nested commas within columns

For a better solution please see the csv module

Note: Pandas has more useful functions for CSV manipulation

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • This is the right way of doing it. – Srikanth Bhandary Mar 11 '18 at 04:21
  • The better way is using a DictReader, though https://docs.python.org/3/library/csv.html#csv.DictReader – OneCricketeer Mar 11 '18 at 04:23
  • Does this work for cell entries escaped by quotes with commas inside? For instance line ="\"City\", \"Austin, TX\"". Expected 2 cells. – MFisherKDX Mar 11 '18 at 04:24
  • @MFisher I appreciate you using my current city, but does the question show such data? – OneCricketeer Mar 11 '18 at 04:26
  • @cricket_007 perhaps you aren't the only SO user in Austin? – hd1 Mar 11 '18 at 04:28
  • 1
    I guess we are neighbors then. :) The question is general. I don't consider myself a "python guy" so I'm curious. This is probably why I'd advise using the built in functions instead of splitting on a comma. I've been burned doing this (splitting on commas) in production code (not python). – MFisherKDX Mar 11 '18 at 04:34
  • @MFisher I think it's a general rule across all languages that if you split a single character from a string, there's no special logic to account for escaped instances of that character. In which case, the `csv` module is better. – OneCricketeer Mar 11 '18 at 15:29
3

Use the csv module:

import csv
with open('examplefile.csv') as tst:
    reader = csv.reader(tst, delimiter=',')
    for line in reader:
        # line is a delimiter-delimited line in your file

Hope that helps.

hd1
  • 33,938
  • 5
  • 80
  • 91