Solved

Python, read CSV file into 1D array, or 2D array into 1D array

Posted on 2011-03-03
4
1,917 Views
Last Modified: 2012-05-11
Hi All

I got the issue to read CSV file into 1D array.

In my csv file, it is only one column.
aaa
bbb
ccc
ddd
eee

After reading CSV file, I got the array key_list:

[['aaa'], ['bbb'], ['ccc']....]

I would like to have 1D array: ['aaa', 'bbb', 'ccc', ......]

How can I read CSV file into 1D array ? or How to make 2D array into 1D array?

Thanks

filename ='test.csv'
    keyreader = csv.reader(open(filename, 'rb'), delimiter= ' ', quotechar='"')
    key_list = []
    for key in keyreader:
        key_list.append(key)
    print key_list

Open in new window

0
Comment
Question by:mxgong
  • 3
4 Comments
 
LVL 28

Expert Comment

by:pepr
ID: 35034327
When iterating through the csv reader object (your line 4 and 5), you get the list representing values from one line of the CSV file.  You have only one element on one line -- so, you get the lists with a single element.  When appending it to another list, you get the list of lists.

This way, your case of processing is somehow special.  Then you can use the .extend() method instead of the .append() at the line 5.
0
 
LVL 28

Expert Comment

by:pepr
ID: 35034355
Fortgot to mention that the lst.extend() appends all the argument elements to the lst that is being extended -- see http://docs.python.org/tutorial/datastructures.html#more-on-lists and http://docs.python.org/library/stdtypes.html#index-632 (rather difficult to understand it from the standard doc).  See "Dive into Python" by Mark Pilgrim, example 3.10. (http://diveintopython.org/native_data_types/lists.html#d0e5887)

You should always explicitly close the open file. This way your open(filename, 'rb', ...) should be called separately (assigning the object to a variable) and should be closed explicitly after the processing).

You should give the 'key' a kind of better identifier as this one causes confusion later.
0
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
ID: 35034396
So, the modified code is:

a.py
import csv

filename ='test.csv'

f = open(filename, 'rb')
reader = csv.reader(f, delimiter= ' ', quotechar='"')
lst = []
for row in reader:
    lst.extend(row)
f.close()
    
print lst

Open in new window


and it prints...

C:\tmp\___python\mxgong\Q_26863285>python a.py
['aaa', 'bbb', 'ccc', 'ddd', 'eee']

Open in new window


The question is what is your final intention.  If the file contains only single elements, no quoting, etc., it may be easier to get the same using a simpler approach:

filename ='test.csv'

f = open(filename)
content = f.read()
f.close()

lst = content.split('\n')
    
print lst

Open in new window


You should also specify bette what do you mean by 1D and 2D array, as there is no standard data type like array in Python.  Arrays are often implemented via lists, the 2D arrays can be implemented via lists of lists.  However, there are packages that implement arrays.
0
 

Author Closing Comment

by:mxgong
ID: 35837075
Sorry for the late
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now