Welcome to Dream.In.Code
Getting Help is Easy!

Join 136,294 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,400 people online right now. Registration is fast and FREE... Join Now!




Reading from a text file into 2D array

 
Reply to this topicStart new topic

Reading from a text file into 2D array, python

rancor
30 Aug, 2008 - 01:06 PM
Post #1

New D.I.C Head
*

Joined: 30 Nov, 2007
Posts: 22



Thanked: 2 times
My Contributions
I've been trying to read floating point literals into a 2D array and have unusual results. When i read this file:
1 1.5 0 2
3 3.25 3 1.67

the code below prints out the list [[1.0, 1.5, 0.0, 2.0], [3.0, 3.25, 3.0, 1.6699999999999999]] . If anyone has any suggestions as to why the final number is approximated or knows of a better way of reading the file, please let me know. Thanks!

CODE

def main():
    DEFAULT_DIR = <put the directory where you store the text file>
    arr = []
    f = open(DEFAULT_DIR + 'input.txt', 'r')
    for line in f:
        arr.append(map(float, line.split()))
        
    print arr

if __name__ == '__main__':
    main()

User is offlineProfile CardPM
+Quote Post

paddy3118
RE: Reading From A Text File Into 2D Array
30 Aug, 2008 - 10:37 PM
Post #2

New D.I.C Head
*

Joined: 28 May, 2007
Posts: 4


My Contributions
QUOTE(rancor @ 30 Aug, 2008 - 02:06 PM) *

I've been trying to read floating point literals into a 2D array and have unusual results. When i read this file:
1 1.5 0 2
3 3.25 3 1.67

the code below prints out the list [[1.0, 1.5, 0.0, 2.0], [3.0, 3.25, 3.0, 1.6699999999999999]] . If anyone has any suggestions as to why the final number is approximated or knows of a better way of reading the file, please let me know. Thanks!



Try this:
http://www.python.org/doc//tut/node16.html
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 05:56AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month