11

I have a CSV file containing the following.

0.000264,0.000352,0.000087,0.000549
0.00016,0.000223,0.000011,0.000142
0.008853,0.006519,0.002043,0.009819
0.002076,0.001686,0.000959,0.003107
0.000599,0.000133,0.000113,0.000466
0.002264,0.001927,0.00079,0.003815
0.002761,0.00288,0.001261,0.006851
0.000723,0.000617,0.000794,0.002189

I want convert the values into an array in Python and keep the same order (row and column). How I can achieve this?

I have tried different functions but ended with error.

7
  • what is error? and how are you attempting to read the csv file? are you using the csv module? Commented May 11, 2016 at 21:53
  • is not a error, I dont know how convert to cvs to array Commented May 11, 2016 at 21:58
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable Example. Commented May 11, 2016 at 22:02
  • Does your CSV file actually contain the parentheses ( )? If so, it's not valid CSV. How was the file generated? Commented May 11, 2016 at 22:05
  • @MattDMo dont have parathesis, do have any idea how I can convert from cvs to array, keep the same orden Commented May 11, 2016 at 22:13

4 Answers 4

20

You should use the csv module:

import csv

results = []
with open("input.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
        results.append(row)

This gives:

[[0.000264, 0.000352, 8.7e-05, 0.000549], 
[0.00016, 0.000223, 1.1e-05, 0.000142], 
[0.008853, 0.006519, 0.002043, 0.009819], 
[0.002076, 0.001686, 0.000959, 0.003107], 
[0.000599, 0.000133, 0.000113, 0.000466], 
[0.002264, 0.001927, 0.00079, 0.003815], 
[0.002761, 0.00288, 0.001261, 0.006851], 
[0.000723, 0.000617, 0.000794, 0.002189]]
Sign up to request clarification or add additional context in comments.

Comments

3

If your file doesn't contain parentheses

with open('input.csv') as f:
    output = [float(s) for line in f.readlines() for s in line[:-1].split(',')]
print(output)

Comments

2

The csv module was created to do just this. The following implementation of the module is taken straight from the Python docs.

import csv 
with open('file.csv','rb') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',', quotechar='|') 
    for row in reader:
        #add data to list or other data structure

The delimiter is the character that separates data entries, and the quotechar is the quotechar.

Comments

-1

For broader usage:

#!/usr/bin/env python3

from pprint import pprint

result = []
delim=','
rows=0

for line in open("input_file.csv"):
    line=line.strip()
    row=line.split(delim)
    result.append(row)
    rows=rows+1

cols=len(row)

pprint(result)
print('rows: '+str(rows))
print('cols: '+str(cols))

# you get array of rows consisting of array of columns, all text

or if you want integers:

#!/usr/bin/env python3

from pprint import pprint

result = []
delim=','
rows=0

for line in open("input_file.csv"):
    line=line.strip()
    row=line.split(delim)
    newrow=[]
    for col in row:
        newrow.append(int(col))
    result.append(newrow)
    rows=rows+1

cols=len(row)

pprint(result)
print('rows: '+str(rows))
print('cols: '+str(cols))

# you get array of rows consisting of array of columns, all integers

Simply change int(col) to float(col) to get floats.

You should get:

[[0.000264, 0.000352, 8.7e-05, 0.000549],
 [0.00016, 0.000223, 1.1e-05, 0.000142],
 [0.008853, 0.006519, 0.002043, 0.009819],
 [0.002076, 0.001686, 0.000959, 0.003107],
 [0.000599, 0.000133, 0.000113, 0.000466],
 [0.002264, 0.001927, 0.00079, 0.003815],
 [0.002761, 0.00288, 0.001261, 0.006851],
 [0.000723, 0.000617, 0.000794, 0.002189]]
rows: 8
cols: 4

6 Comments

This is fairly unidiomatic and verbose. Just use the csv module which copes correctly with quoted values etc. The old answer by James Buck is more indicative of how you would write the simple loop in Python if you want to avoid the standard csv module for some reason.
@tripleee This code is for extending purposes if someone would like to.
But then why would they not extend the csv module, which already has many options to configure its behavior?
@tripleee Because of different data in csv file. Treat it as tutorial for less advanced users.
But then shouldn't you teach them to close the file when they are done, and use enumerate, and/or trust that len(result) correctly identifies the number of rows? And probably check that the number of columns is consistent across rows.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.