faqts : Computers : Programming : Languages : Python : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 9 people (56%) answered Yes
Recently 5 of 9 people (56%) answered Yes

Entry

How to write a specific line in a file content?

Mar 31st, 2006 00:37
Sean Reece, eric huang,


It's not too hard to do. It takes advantage of the fact that when you
use the readline() module, it advances the location of the pointer in
the memory by one line, so consecutive readline calls can net you the
line you want. 

Put this function in your script, or put it in a separate file and
import it. 
---------------------------------------------
def writeline(lineno,linetext,filename):
     file=open(filename, "r+")
     y=1
     while y<lineno:
          file.readline()
          y=y+1
     file.writelines(linetext)
     file.close()
---------------------------------------------

I hope this helps you!

Reading a specific line is even easier.
-------------------------------------------- 
def readline(lineno, filename):
     file=open(filename, "r")
     y=1
     while y<lineno:
          file.readline()
          y=y+1
     content=file.readline()
     #uncomment the next line if you want the newline char stripped from
everything that's loaded
     #content-content.strip()
     return content
--------------------------------------------

So if line 3 in linux.txt says LINUX, then readline(3, "linux.txt") will
return LINUX, meaning that readline(3, "linux.txt")==LINUX