473,721 Members | 2,252 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need Help Parsing From File

Hi, I've got a Python program that I'm trying to edit, and I need some
help.

If I would like to read a matrix from a previously created text file
into a two dimensional array, how would I do that?

Like, if in the txt file, I had the following matrix formatted numbers
with 5 rows and 10 columns, and each number is separated by a single space:

11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60

How would I read this data from the file into a two dimensional array in
Python?
Dec 7 '06 #1
12 1313
John Frame wrote:
How would I read this data from the file into a two dimensional array in
Python?
Like:
[x.split() for x in open('myfile.tx t')]

Or if you need integers:
[[int(a) for a in x.split()] for x in open('myfile.tx t')]

;)
--
Soni Bergraj
http://www.YouJoy.org/
Dec 7 '06 #2
At Thursday 7/12/2006 00:20, John Frame wrote:
>Like, if in the txt file, I had the following matrix formatted numbers
with 5 rows and 10 columns, and each number is separated by a single space:

11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60

How would I read this data from the file into a two dimensional array in
Python?
If "two dimensional array" means "a list of 5 elements each one being
a list of 10 integers" you can do this:

ftxt=open(filen ame,"rt")
arr = []
for line in ftxt:
arr.append([int(number) for number in line.split()])
ftxt.close()

or, not so legible but more compact:

ftxt=open(filen ame,"rt")
arr2 = [[int(number) for number in line.split()] for line in ftxt]
ftxt.close()

or using Python 2.5:

with open(filename," rt") as ftxt:
arr3 = [[int(number) for number in line.split()] for line in ftxt]
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 7 '06 #3

Gabriel Genellina wrote:
>
ftxt=open(filen ame,"rt")
Never seen that done before. It's not in the docs.

FWIW:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright" , "credits" or "license" for more information.
>>f = open('foo.txt', 'rt')
f = open('foo.txt', 'rs')
f = open('foo.txt', 'ratsdroppings' )
# Nary an exception raised, not the slightest murmur

Is this a bug or a feature? Or is it one of those good old "unspecifie d
behaviour" cases? MSVC rtl only?

Cheers,
John

Dec 7 '06 #4
At Thursday 7/12/2006 02:51, John Machin wrote:
>Gabriel Genellina wrote:

ftxt=open(filen ame,"rt")

Never seen that done before. It's not in the docs.
A remnant of my MSDOS+C background...
>FWIW:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright" , "credits" or "license" for more information.
>f = open('foo.txt', 'rt')
f = open('foo.txt', 'rs')
f = open('foo.txt', 'ratsdroppings' )
# Nary an exception raised, not the slightest murmur

Is this a bug or a feature? Or is it one of those good old "unspecifie d
behaviour" cases? MSVC rtl only?
The Python docs say only that the initial letter is checked. And the
ANSI 89 C says that other characters may follow after r, r+, etc.
"rt" is useless for an ANSI C compiler, since the default stream mode
is "text" -on systems which differentiate between text and binary-
and irrelevant on systems which don't do such distinction.
(And since I got used to write "rt", you can infer something about
*when* I began to write C programs...)
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 7 '06 #5

Gabriel Genellina wrote:
At Thursday 7/12/2006 02:51, John Machin wrote:
Gabriel Genellina wrote:
>
ftxt=open(filen ame,"rt")
Never seen that done before. It's not in the docs.

A remnant of my MSDOS+C background...
FWIW:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright" , "credits" or "license" for more information.
>>f = open('foo.txt', 'rt')
>>f = open('foo.txt', 'rs')
>>f = open('foo.txt', 'ratsdroppings' )
# Nary an exception raised, not the slightest murmur

Is this a bug or a feature? Or is it one of those good old "unspecifie d
behaviour" cases? MSVC rtl only?

The Python docs say only that the initial letter is checked. And the
ANSI 89 C says that other characters may follow after r, r+, etc.
"rt" is useless for an ANSI C compiler, since the default stream mode
is "text" -on systems which differentiate between text and binary-
and irrelevant on systems which don't do such distinction.
(And since I got used to write "rt",
Why did you do that?
(1) Text mode is was and ever shall be the default, even with MS.
(2) Seeing we're referring to docs and standards: Microsoft C 5.0
Optimizing Compiler, Run-Time Library Reference manual says "The t
option is not part of the ANSI standard for open, but is a Microsoft
extension and should not be used where ANSI portability is required".
you can infer something about
*when* I began to write C programs...)
Youngster :-)

Cheers,
John

Dec 7 '06 #6
At Thursday 7/12/2006 15:44, John Machin wrote:
ftxt=open(filen ame,"rt")
>
>Is this a bug or a feature? Or is it one of those good old "unspecifie d
>behaviour" cases? MSVC rtl only?
The Python docs say only that the initial letter is checked. And the
ANSI 89 C says that other characters may follow after r, r+, etc.
"rt" is useless for an ANSI C compiler, since the default stream mode
is "text" -on systems which differentiate between text and binary-
and irrelevant on systems which don't do such distinction.
(And since I got used to write "rt",

Why did you do that?
(1) Text mode is was and ever shall be the default, even with MS.
No, there used to be a flag in the stdio library, giving the default
value when neither t or b was specified.
For the Borland C++ 3.1 help (about 1991):
If "t" or "b" is not given in the string, the mode is governed by _fmode.
If _fmode is set to O_BINARY, files are opened in binary mode.
If _fmode is set to O_TEXT, they are opened in text mode.
MSC used to have a similar flag (perhaps using the same name).
All of this predates wide usage of ANSI C 89, which made the "t" flag obsolete.
>(2) Seeing we're referring to docs and standards: Microsoft C 5.0
Optimizing Compiler, Run-Time Library Reference manual says "The t
option is not part of the ANSI standard for open, but is a Microsoft
extension and should not be used where ANSI portability is required".
A "t" after the initial recognized characters should be ignored by
any conforming compiler. I think the idea was to allow for extensions
like fopen(fn, "rt;reclen=128" ) but except esoteric platforms I doubt
anyone is using that.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 8 '06 #7
On 8/12/2006 1:53 PM, Gabriel Genellina wrote:
At Thursday 7/12/2006 15:44, John Machin wrote:
ftxt=open(filen ame,"rt")

Is this a bug or a feature? Or is it one of those good old
"unspecifie d
>behaviour" cases? MSVC rtl only?

The Python docs say only that the initial letter is checked. And the
ANSI 89 C says that other characters may follow after r, r+, etc.
"rt" is useless for an ANSI C compiler, since the default stream mode
is "text" -on systems which differentiate between text and binary-
and irrelevant on systems which don't do such distinction.
(And since I got used to write "rt",

Why did you do that?
(1) Text mode is was and ever shall be the default, even with MS.

No, there used to be a flag in the stdio library, giving the default
value when neither t or b was specified.
For the Borland C++ 3.1 help (about 1991):
If "t" or "b" is not given in the string, the mode is governed by _fmode.
If _fmode is set to O_BINARY, files are opened in binary mode.
If _fmode is set to O_TEXT, they are opened in text mode.
MSC used to have a similar flag (perhaps using the same name).
Indeed, and their docs say that the default for _fmode is text mode.
All of this predates wide usage of ANSI C 89, which made the "t" flag
obsolete.
>(2) Seeing we're referring to docs and standards: Microsoft C 5.0
Optimizing Compiler, Run-Time Library Reference manual says "The t
option is not part of the ANSI standard for open, but is a Microsoft
extension and should not be used where ANSI portability is required".

A "t" after the initial recognized characters should be ignored by any
conforming compiler. I think the idea was to allow for extensions like
fopen(fn, "rt;reclen=128" ) but except esoteric platforms I doubt anyone
is using that.
So it should be ignored.

So, back to the question: why did you get into the habit of writing "rt"
when it was pointless?

Dec 8 '06 #8
John Machin wrote:
Indeed, and their docs say that the default for _fmode is text mode.
the default doesn't matter much if you're writing library code for an
application that may change it.

</F>

Dec 8 '06 #9
At Friday 8/12/2006 02:23, John Machin wrote:
> ftxt=open(filen ame,"rt")

Why did you do that?
(1) Text mode is was and ever shall be the default, even with MS.
No, there used to be a flag in the stdio library, giving the
default value when neither t or b was specified.
For the Borland C++ 3.1 help (about 1991):
If "t" or "b" is not given in the string, the mode is governed by _fmode.
If _fmode is set to O_BINARY, files are opened in binary mode.
If _fmode is set to O_TEXT, they are opened in text mode.
MSC used to have a similar flag (perhaps using the same name).
Indeed, and their docs say that the default for _fmode is text mode.
But anyone could change that *global* flag, making "binary" the
default afterwards. So if you really wanted a text file you had to be explicit.
>>All of this predates wide usage of ANSI C 89, which made the "t"
flag obsolete.
>>>(2) Seeing we're referring to docs and standards: Microsoft C 5.0
Optimizing Compiler, Run-Time Library Reference manual says "The t
option is not part of the ANSI standard for open, but is a Microsoft
extension and should not be used where ANSI portability is required".
A "t" after the initial recognized characters should be ignored by
any conforming compiler. I think the idea was to allow for
extensions like fopen(fn, "rt;reclen=128" ) but except esoteric
platforms I doubt anyone is using that.

So it should be ignored.
So, back to the question: why did you get into the habit of writing
"rt" when it was pointless?
Because it was *not* pointless before ANSI C.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 8 '06 #10

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

Similar topics

2
3956
by: Cigdem | last post by:
Hello, I am trying to parse the XML files that the user selects(XML files are on anoher OS400 system called "wkdis3"). But i am permenantly getting that error: Directory0: \\wkdis3\ROOT\home Canonicalpath-Directory4: \\wkdis3\ROOT\home\bwe\ You selected the file named AAA.XML getXmlAlgorithmDocument(): IOException Not logged in
0
1571
by: Doug R | last post by:
Hello, I have a system that I am writing to automaticly import Credit Transaction data into a SQL Server 2000 Database. I am using a VB.Net application to detect when the file arives and prep it for parsing. The file is aproximately 10Mb of relatively complex hierarchal data that is defined by 2 character tokens at the begining of each data line. The structure breaks out into aproximately 6 parent-child related tables with numerous...
1
1722
by: sommarlov | last post by:
Hi everyone >From one of our systems an xml file is produced. I need to validate this file before we send it to an external system for a very lenghty process. I cannot change the xml file layout. The solution i got today is very slow, and i need help to find another solution. Here is the xml file. It consists of a list of position ids (ESTOXX50 INDEX_BM_E and FTSE INDEX_BM_E), and below that a list of tags for each position id. What i...
4
4859
by: Rick Walsh | last post by:
I have an HTML table in the following format: <table> <tr><td>Header 1</td><td>Header 2</td></tr> <tr><td>1</td><td>2</td></tr> <tr><td>3</td><td>4</td></tr> <tr><td>5</td><td>6</td></tr> </table> With an XSLT styles sheet, I can use for-each to grab the values in
27
5140
by: comp.lang.tcl | last post by:
My TCL proc, XML_GET_ALL_ELEMENT_ATTRS, is supposed to convert an XML file into a TCL list as follows: attr1 {val1} attr2 {val2} ... attrN {valN} This is the TCL code that does this: set contents ]; close $fileID
9
1986
by: Paulers | last post by:
Hello, I have a log file that contains many multi-line messages. What is the best approach to take for extracting data out of each message and populating object properties to be stored in an ArrayList? I have tried looping through the logfile using regex, if statements and flags to find the start and end of each message but I do not see a good time in this process to create a new instance of my Message object. While messing around with...
2
1807
by: Anders B | last post by:
I want to make a program that reads the content of a LUA array save file.. More precicely a save file from a World of Warcraft plugin called CharacterProfiler, which dumps alot of information about your characters into that save file. Anyhow, I want to extract a couple of lines of it and save it into a database and I need help on figuring out a good way of reading the file. The problem is that the file can look pretty different depending...
25
3121
by: Jon Slaughter | last post by:
I have some code that loads up some php/html files and does a few things to them and ultimately returns an html file with some php code in it. I then pass that file onto the user by using echo. Of course then the file doesn't get seen by the user. Is there any command that essentially executes the code and then echo's it? something that will take a string like '<body>blah<?php echo 'Hello'; ?></body>' and actually interpret the php
4
1902
by: Tom | last post by:
I am trying to update another developers code, and am stuck in a cludge. It works like this: A user uploads a file from the web page. Our code reads from a NetworkStream to a Filestream, and writes out a temporary file. Then the file is parsed (The file contains HTML data + the actual binary file that was transmitted). As part of the parsing, once the main binary file is to be parsed out, it is written with a new Filestream,
6
1669
by: Damien87 | last post by:
Hi, I have a .data file which is essentially just a text file with a bunch of numbers. It's in the format "xx yy zzz abc ccf fffd sss xxx xx sss qq" Basically it is a random amount of numbers per line separated using spaces (not tabs or commas). What I need to do is parse the file to a format which would be more suitable to use for a SQl database system I am implementing. I need the output file to look like "1,xx 1,yy 1,zzz
0
8736
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
9227
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...
1
9138
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9074
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...
0
8016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5992
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
4761
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3201
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
2584
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.