0

I currently have a text file I am reading from that contains 6 numbers that I need to be able to call individually.

The text file looks like this

11 12 13

21 22 23

So far I've used the following to try to get the correct output with no success.

with open(os.path.join(path,"config.txt"),"r") as config:
    mylist = config.read().splitlines() 
    print mylist

This gives me ['11 12 13', '21 22 23'].

with open(os.path.join(path,"config.txt"),"r") as config:
    contents = config.read()
    params = re.findall("\d+", contents)
    print params

This gives me ['11', '12', '13', '21', '22', '23']

with open(os.path.join(path,"config.txt"),"r") as config:
    for line in config:
        numbers_float = map(float, line.split())
        print numbers_float[0]

This gives me 11.0 21.0

The last method is the closest but gives me both numbers in the first column instead of just one.

Also would I be able to separate the numbers in the text file with commas with the same or better result?

Thanks for any help!

Jack Hunt
  • 3
  • 1
  • 1
    What exactly is your desired output? Also, why have you tagged this `int` but used `float` in you code? Which one do you want? And how is the `cloud9` tag relevant? – abarnert Mar 25 '18 at 23:01

1 Answers1

1

Your last one is close—you're creating a list of float for each numeral in each line; the only problem is that you're only using the first one. You need to loop over the list:

with open(os.path.join(path,"config.txt"),"r") as config:
    for line in config:
        numbers_float = map(float, line.split())
        for number in numbers_float:
            print number

You could also flatten things out

with open(os.path.join(path,"config.txt"),"r") as config:
    splitlines = (line.split() for line in file)
    flattened = (numeral for line in splitlines for numeral in line)
    numbers = map(float, flattened)
    for number in numbers:
        print number

Now that it's just a chain of iterator transformations you can make that chain more concise if you want:

with open(os.path.join(path,"config.txt"),"r") as config:
    numbers = (float(numeral) for line in file for numeral in line.split())
    for number in numbers:
        print number

… but I don't think that's actually clearer, especially to a novice.

abarnert
  • 354,177
  • 51
  • 601
  • 671