School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,149 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,708 people online right now. Registration is fast and FREE... Join Now!




python- import numbers from file to do calcs

 

python- import numbers from file to do calcs

crocadilekyle

1 Oct, 2009 - 07:58 PM
Post #1

New D.I.C Head
*

Joined: 2 Aug, 2009
Posts: 29

So i am trying to write some code (in Python) that will import some numbers from a file. I was thinking maybe to import them into a list so that way I can do calculations with them using a for loop or something...

Here is the code that writes numbers to a file.

CODE


import math

myfile = open('myfile.py', 'w')

L1 = [1,2,3,4,5]
for i in L1:
      a = math.pi*(i**2)
      myfile.write( repr(a))
      myfile.write("\n")
        
myfile.close()



and here is the code that imports the numbers from a file and I would like them to import into a list. unless someone has a better idea....

CODE

myfile = open('myfile.py', 'r');
i=0

while i < 5:
    print myfile.readline()
    i = i+1
    



Any help is appreciated.

User is offlineProfile CardPM
+Quote Post


Nallo

RE: Python- Import Numbers From File To Do Calcs

3 Oct, 2009 - 04:30 AM
Post #2

New D.I.C Head
*

Joined: 19 Jul, 2009
Posts: 24



Thanked: 3 times
My Contributions
Take a look at the list methods in the Pythondocumentation. In your case you need list.append().
li.append(new_element) appends new_element to an existing list li.

CODE
li = []
for i in range(5):
    line = myfile.readline()

    line = line.rstrip() #remove the trailing whitespace, especially the newline character
    number = float(line) #convert the string back to a number

    li.append(number)

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 04:17PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month