1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python: open dat-files, read data

  1. Oct 18, 2008 #1
    1. The problem statement, all variables and given/known data
    I have two programs and neither works. In the first program I don't get any autput from andre(f):

    f = open("densities.dat", "r")

    def andre(f):
    densities = {}
    for line in f:
    density = float(line[12:])
    name = line[0:10].strip()
    densities[name] = density

    return densities

    and in the second program I want to be able to use the numbers and get therfor strip "," and make a float

    from math import *
    f = open("output.txt", "r")
    print type(1e-4)
    epsilon = []
    exact_error = []
    n = []
    for line in f:
    words = line.split(",")
    words = line.split()
    print float(words[1].strip(","))
     

    Attached Files:

  2. jcsd
  3. Oct 18, 2008 #2
    I didn't manage to upload densities.dat
    densities.dat
    air 0.0012
    gasoline 0.67
    ice 0.9
    pure water 1.0
    seawater 1.025
    human body 1.03
    limestone 2.6
    granite 2.7
    iron 7.8
    silver 10.5
    mercury 13.6
    gold 18.9
    platinium 21.4
    Earth mean 5.52
    Earth core 13
    Moon 3.3
    Sun mean 1.4
    Sun core 160
    proton 2.8E+14
     
  4. Oct 20, 2008 #3
    I got the answear and I will post it later today.
     
  5. Oct 19, 2011 #4
    so what was the solution after all ?
     
  6. Oct 19, 2011 #5
    I'm sorry, but I don't longer know and I'm no longer able to find the solution.
    Again I should have posted my solution.
     
  7. Oct 19, 2011 #6

    phyzguy

    User Avatar
    Science Advisor

    You opened the file, but you didn't read the file. Normally the sequence goes something like this:

    Code (Text):

    file = open("filename","r")
    lines = file.readlines() # This is what you forgot
    file.close()
    for line in lines:
       name = float(line.strip().split()[0]) # Or something like this...
       ...
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Python: open dat-files, read data
  1. Reading a File (Replies: 2)

Loading...