Movatterモバイル変換


[0]ホーム

URL:


insert line in middle of file

Alex Martellialeaxit at yahoo.com
Mon Apr 2 15:13:09 EDT 2001


"Kragen Sitaker" <kragen at dnaco.net> wrote in messagenews:N13y6.19325$BC6.5304590 at e3500-chi1.usenetserver.com...> In article <9aacgo$7da$1 at solaria.cc.gatech.edu>,> Holland King  <insanc at cc.gatech.edu> wrote:> >i have a file that must have some stuff at the beginning and the end andi> >need to add a line to the middle. is there any easy way to do thiswithout> >losing data? thank you.>> Copy the beginning to a new file, write the added line to the new file,> and copy the end to the new file.  Then rename the new file to have the> same name as the old one.Excellent summary of the needed underlying operations.  I'd justlike to add that the standard Python fileinput module may be a goodway to wrap these operations up in certain cases, at a somewhathigher logical level, thanks to the 'inplace' and 'backup' arguments.E.g., say you want to rewrite ``in-place'' a file "a.txt" by adding aline "Foopie!" each time it now has a like starting with a lowercase'x' (peculiar task, but we have all seen worse:-).  fileinput makesthis pretty easy:import fileinputfor line in fileinput.input('a.txt',inplace=1):    print line[:-1]    if line.startswith('x'): print "Foopie!"Standard output is redirected to (a fresh version of) the file(s)being read, so you only need to 'print' right back any line youwant to "preserve" (here, all of them) -- just remember thatprint adds a newline, so you need to remove the trailing onesalready present in the lines you have read -- and add orsubstitute, again with 'print', whatever new or changed linesyou wish (you can also 'delete', so to speak, any input lines,by just not printing them out again...).In other cases, of course, one may prefer to have all the textin memory at once (as a list of lines), edit it appropriatelywith list means (assignment to list-slices being very good forsuch editing:-), and write it out again with .writelines...Alex


More information about the Python-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp