Prometheus
Prometheus

Reputation: 33615

Using Python to loop contents of a CSV

In Python I want to list out each number inside a simple CSV...

CSV:

07555555555, 07555555551

This is what I have tried:

for number in csv.reader(instance.data_file.read().splitlines()):
    print(number)

However, this outputs the whole thing as one string like this...

['07446164630', '07755555555']

Why?

I have also tried to loop like this

for i, item in enumerate(csv.reader(instance.data_file.read().splitlines())):
    print(i)
    print(item)

I'm not sure I fully understand what I'm doing wrong so any help in explaining how to print each number in the file would be amazing.

Upvotes: 0

Views: 82

Answers (2)

Kroltan
Kroltan

Reputation: 5156

csv.reader parses each line of a CSV, so your loop is iterating over the lines of the CSV file. Since both numbers are in one line, you get them in one array. If you want to iterate on the values of each line, use another, nested for loop.:

for line in csv.reader(instance.data_file.read().splitlines()):
    for item in line:
        number = int(item)
        print(number) # or whatever you want

Or using enumerate to get the indices of each number:

for line in csv.reader(instance.data_file.read().splitlines()):
    for index, item in enumerate(line):
        number = int(item)
        print(index, number) # or whatever you want

Upvotes: 2

Irshad Bhat
Irshad Bhat

Reputation: 8709

Use numpy's flatten module to convert matrices to 1D arrays:

import numpy as np
data = np.loadtxt(file_name, delimiter=',').flatten()
for item in data: print(item)

Upvotes: -1

Related Questions