473,698 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[2.5] Reading a two-column file into an array?

Hello

I'm sure there's a much easier way to read a two-column, CSV file into
an array, but I haven't found it in Google.

Should I use the Array module instead?

=========
a = []
i = 0

#item<TAB>item< CRLF>
p = re.compile("^(. +)\t(.+)$")

for line in textlines:
m = p.search(line)
if m:
a[i,0] = m.group(1)
a[i,1] = m.group(2)
i = i + 1

for i in a.count:
for j in 2:
print a[i,j]
=======

Thank you.
Jul 31 '07 #1
6 3944
Gilles Ganault wrote:
I'm sure there's a much easier way to read a two-column, CSV file into
an array, but I haven't found it in Google.

Should I use the Array module instead?
The csv module? Or just .rstrip and .split?

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
I get my kicks above the wasteline, sunshine
-- The American, _Chess_
Jul 31 '07 #2
On Jul 31, 9:03 am, Gilles Ganault <nos...@nospam. comwrote:
Hello

I'm sure there's a much easier way to read a two-column, CSV file into
an array, but I haven't found it in Google.

Should I use the Array module instead?

=========
a = []
i = 0

#item<TAB>item< CRLF>
p = re.compile("^(. +)\t(.+)$")

for line in textlines:
m = p.search(line)
if m:
a[i,0] = m.group(1)
a[i,1] = m.group(2)
i = i + 1

for i in a.count:
for j in 2:
print a[i,j]
=======

Thank you.
a = []
import csv
reader = csv.reader(open ("filename", "r"), delimiter='\t' )
for row in reader:
a.append( row )

----------------------------
I don't think you can have multidimensiona l arrays.
Did you test you program? It did not work for me.
I think mine would suit your requirements as the output is a list of
lists.
Jul 31 '07 #3
Nagarajan wrote:
On Jul 31, 9:03 am, Gilles Ganault <nos...@nospam. comwrote:
>Hello

I'm sure there's a much easier way to read a two-column, CSV file into
an array, but I haven't found it in Google.

Should I use the Array module instead?
[...snip]
a = []
import csv
reader = csv.reader(open ("filename", "r"), delimiter='\t' )
for row in reader:
a.append( row )

----------------------------
I don't think you can have multidimensiona l arrays.
Did you test you program? It did not work for me.
I think mine would suit your requirements as the output is a list of
lists.
I am similarly confused as to the nature of the original request, but for completeness' sake, I went by the same assumption of building a list of lists, and came up with this (which does not use the csv module). Nagarajan's code is more concise and just as readable IMO, but here's my take anyway:

a = []
b = []
handle = open(filename, 'r')

for line in handle.xreadlin es():
col1,col2 = line.split('\t' )
a.append(col1)
b.append(col2)

columns = [a, b]

-Jay
Jul 31 '07 #4
On Mon, 30 Jul 2007 21:57:17 -0700, Nagarajan wrote:
a = []
import csv
reader = csv.reader(open ("filename", "r"), delimiter='\t' )
for row in reader:
a.append( row )
I would keep a reference to the file to close it properly and the loop can
be replaced by a call to `list()`:

import csv

def main():
data_file = open('filename' , 'rb')
a = list(csv.reader (data_file, delimiter='\t') )
data_file.close ()

Ciao,
Marc 'BlackJack' Rintsch
Jul 31 '07 #5
Marc 'BlackJack' Rintsch <bj****@gmx.net wrote:
On Mon, 30 Jul 2007 21:57:17 -0700, Nagarajan wrote:
a = []
import csv
reader = csv.reader(open ("filename", "r"), delimiter='\t' )
for row in reader:
a.append( row )

I would keep a reference to the file to close it properly and the loop can
be replaced by a call to `list()`:

import csv

def main():
data_file = open('filename' , 'rb')
a = list(csv.reader (data_file, delimiter='\t') )
data_file.close ()
That's what 2.5's with statement is all about...:

from __future__ import with_statement

def main():
with open('filename' , 'rb') as f:
return list(csv.reader (f, delimiter='\t') )
Alex
Jul 31 '07 #6
On Tue, 31 Jul 2007 08:41:45 -0700, al***@mac.com (Alex Martelli)
wrote:
>That's what 2.5's with statement is all about...:
Thanks everyone. Python power :-)

from __future__ import with_statement
import csv

with open('import.cs v', 'rb') as f:
for item in list(csv.reader (f, delimiter='\t') ):
print item[0] + "," + item[1]
Aug 2 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1012
by: Webster | last post by:
Hello, I have a program that asynchronously reads data from a host. However, whenever I call the BeginRead function, the async reading "loop" never seems to terminate. Why doesn't the EndRead method return 0 when it is done reading?? This is the pseudo-code for my callback function: ReadData
1
2085
by: SteveB | last post by:
I'm porting an application from Apache Xerces to .Net and am having a couple of small problems with deserialization. The XML that I'm reading comes from a variety of sources, and there are two inconsistencies that Xerces is able to handle that XmlSerializer seems not to be able to deal with. 1) Some of the boolean values that I'm dealing with are "True" and "False" rather than "true" and "false". I'm not quite sure whether "True" and...
3
2301
by: fuenfzig | last post by:
Hi all, I want to use a single std::stringbuf for writing (by a std::ostream) and for reading (by a std::istream), concurrently in two threads. This came to my mind, because the code for reading should be as with any other istream and cannot be changed. Now my problem is, that a do not get any data in the reading loop std::ofstream tempfile("test.pdf", std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);...
10
8351
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's NumPy manual, I have a quick question (hopefully) regarding how to read in Fortran written data. The data files are not binary, but ASCII text files with no formatting and mixed data types (strings, integers,...
70
3492
by: hstagni | last post by:
When i read a key using getchar() inside a loop, the program stops and wait for a key to be pressed. I actually want the program to continue its execution until a key is pressed. Look at this sample: ------ while(1=1) { printf("oi"); ch=getchar(); if (ch=='q') break; }
9
1821
by: Bill Woessner | last post by:
Suppose I have a structure, foo, which is a POD. I would like to read and write it to disk as follows: std::ofstream outs; foo bar; outs.write(reinterpret_cast<char*>(&bar), sizeof(foo)); .... std::ifstream ins; foo bar; ins.read(reinterpret_cas<char*>(&bar), sizeof(foo));
4
2100
by: Shark | last post by:
Hi, I need a help. My application reads data from COM port, this data is then parsed and displyed on: 1. two plotters 2. text box. I'm using Invoke method to update UI when new data is received (through delegate).
9
14393
by: Hal Vaughan | last post by:
I've done a fair amount of Googling for information on reading the serial port in C++ (and in Linux). Unfortunately, out of every 4 hits, 1 seems to be an unanswered question, 1 is someone saying, "That's easy, there's a lot out there, Google it,", 1 is a discussion on it without examples and the other is who knows what. I did find some info on it and have been experimenting. The one example that I liked the best in terms of...
19
2304
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
6
3784
by: rahul | last post by:
I am reading a binary packet : 32, 8, 8, 2, 1, 1, 4, 128 I am using the following structure to parse the data: struct header { unsigned int a:32; unsigned int b:8; unsigned int c:8; unsigned int d:2; unsigned int e:1; unsigned int f:1; unsigned int g:4;
0
8598
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9014
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8855
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4612
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2320
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.