user202081
user202081

Reputation:

Python auto define variables

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

Upvotes: 1

Views: 948

Answers (2)

John La Rooy
John La Rooy

Reputation: 304205

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)

Upvotes: 13

Kugel
Kugel

Reputation: 19824

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

Upvotes: 1

Related Questions