1

I am new to programming and am learning Python as my first language. I have been tasked with writing a script that converts one input file type to another. My problem is this: There is one part of the input files where there can be any number of rows of data. I wrote a loop to determine how many rows there are but cannot seem to write a loop that defines each line to its own variable eg: rprim1, rprim2, rprim3, etc. This is the code I am using to pull variables from the files:

rprim1=linecache.getline(infile,7)

To reiterate, I would like the parser to define however many lines of data there are, X, as rprimx, with each line,7 to 7+X.

Any help would be appreciated.

Thanks

AFoglia
8,1683 gold badges38 silver badges52 bronze badges
asked Nov 3, 2009 at 21:29

2 Answers 2

13

You can dynamically create the variables, but it doesn't make sense unless this is homework.

instead use

rprim=infile.readlines()

then the lines are

rprim[0], rprim[1], rprim[2], rprim[3], rprim[4], rprim[5], rprim[6]

you can find out how many rows there are with

len(rprim)
answered Nov 3, 2009 at 21:34
Sign up to request clarification or add additional context in comments.

2 Comments

Can't + this enough. There is no rational reason to create variables when all you really need is a simple data structure. You'll save yourself infinite headache, simplify your memory management, and gain some handy functions.
Now I see what I should have been doing all along. Still learning to think like a programmer...with lists... Thank You
1

That is something you really don't want. Suppose you have those variables rprim1, rprim2 .. etc how would you know how many of them do you have?

Read up on lists in python link text

answered Nov 3, 2009 at 21:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.