1

I have a text file:

30.154852145,-85.264584254
15.2685169645,58.59854265854
...

I have the following python script:

count = 0

while True:
        count += 1
        print 'val:',count
        for line in open('coords.txt'):
                c1, c2 = map(float, line.split(','))
                break
        print 'c1:',c1
        if count == 2: break

I want c1 = 15.2685169645 for val: 2. Can someone please tell me what I am messing up on?

1
  • An nice alternative for reading csv-files containing numerical data in python is to use numpy.genfromtxt. Another one is pandas.read_csv. Commented Oct 31, 2014 at 14:26

2 Answers 2

3

By reopening the file each time, you start reading from the start again.

Just open the file once:

with  open('coords.txt') as inputfile:
    for count, line in enumerate(inputfile, 1):
        c1, c2 = map(float, line.split(','))
        print 'c1:',c1
        if count == 2: break

This also uses the file object as a context manager so the with statement will close it for you once done, and uses enumerate() to do the counting.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks...I actually need the while loop in there for other computations...please read my message to @Cyber below. can you please edit it with the code I put up?
@user2468702: you'd still use the with statement to open the file object just once. Put your while loop where the for loop is now, and call inputfile.readline() or next(inputfile) to get your next line.
1

Using your own loop:

with open('coords.txt') as f:
    count = 1
    while True:
        for line in f:
            print 'val: {}'.format(count)
            c1, c2 = map(float, line.split(','))
            print("c1 = {!r}".format(c1))
            if count == 2:
                break
            count += 1
        break

10 Comments

thanks for replying, but it is not working still..I may be missing something still...it just outputs c1 = 30.154852145...I want the if statement to dictate how many values of c1 I want...so if I say if count == 2 then it should output c1 = 30.154852145 in the first loop and then c1 = 15.2685169645 in the next iteration
I edited but unless you are doing something outside the for loop with the values, the while loop is unnecessary
I am sorry...it is doing that, but it does not output the previous one....say I have 4 total coords and I set the if statement to break at count == 3 then I would like to have the first three values output at each run of the while loop..if this makes sense?
I have edited to output all values up to and including count but as I said in my comment you can do this with just the for loop
awesome...this is what I needed...thanks a lot...however it does not output all the decimal places -- is it possible to get all of them?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.