Solved

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

Posted on 2011-03-03
4
1,960 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
None is returned 6 40
python - upgrading from vers 3.4.1 to 3.5.2 - advice requested 7 127
Perl Frameworks 1 79
Reading text file in Python gives strange results 7 67
Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

910 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

18 Experts available now in Live!

Get 1:1 Help Now