PDA

View Full Version : Python: set a string to line x of theFile




lynkynpark86
Nov 29, 2011, 11:30 AM
I'm making a program that reads and writes files for a specific purpose, and I need to be able to basically do this:

theString = theFile.line(2)

to set theString to whatever text is on line 2 of theFile. Any suggestions?



cm2
Nov 29, 2011, 12:05 PM
If the file is not too large, then you can just read it into an array and then select the line you want:

theString = theFile.readlines()[x-1]

Recall that this is zero-based indexing, hence the -1.

lynkynpark86
Nov 29, 2011, 02:06 PM
If the file is not too large, then you can just read it into an array and then select the line you want:

theString = theFile.readlines()[x-1]

Recall that this is zero-based indexing, hence the -1.

So for line 1 do x-0, and line 3, x-2?

cm2
Nov 29, 2011, 03:51 PM
So for line 1 do x-0, and line 3, x-2?

No, if you want line number x, then just replace the x in the code with your line number. For example, if you want the 5th line of the file, set x=5 before the line I gave you.

My comment about the -1 was just to note that line 1 of the file is actually index 0, line 2 is index 1, etc. of the list returned by readlines(). The index you want from the list will always be the line number you want minus 1.