0

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.

4
  • 1
    You can iterate the list you are getting while reading the csv file and print it. Commented Dec 2, 2014 at 12:07
  • 1
    @TanveerAlam thanks, is that the correct way tho seems too simple? I also assumed thats what enumerate would do, but had not joy. Commented Dec 2, 2014 at 12:09
  • 2
    Your csv has just a line of 2 elements so it is returning just a list of two elements like print(['07446164630', '07755555555']) Commented Dec 2, 2014 at 12:10
  • @OrbiterFleet : Yes you can read rows which returns list which can be iterated. Commented Dec 2, 2014 at 12:18

2 Answers 2

2

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

2 Comments

@OrbiterFleet Yes, enumerate can be used with any list.
If this solves your question, feel free to click the checkmark to the left. Or you can wait for another answer that you might like more.
-1

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)

1 Comment

A bit overkill, don't you think? Also, he didn't say what should happen when there is more than one line. It may or not be what he intends.

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.