Python: set a string to line x of theFile

Discussion in 'Mac Programming' started by lynkynpark86, Nov 29, 2011.

  1. lynkynpark86 macrumors 6502

    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?
  2. cm2 macrumors newbie

    Nov 29, 2011
    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.
  3. lynkynpark86 thread starter macrumors 6502

    So for line 1 do x-0, and line 3, x-2?
  4. cm2 macrumors newbie

    Nov 29, 2011
    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.

Share This Page