Replacing a section of text in one file with text from another using python -
first bit of background: yes, new python, dabble , learn things.
the goal this: have intranet website here @ work , have on static server no server side scripting allowed, meaning no php. add new pages, must update every freakin page's menu new link. fortunately, have application called arcgis installed on computer , came installation of python. thinking nice put script read file called "menu.txt" , search recursively in directory (and subdirectories) files ".html" , replace text between comment tags, <!--begin menu-->
, <!--end menu-->
, text in "menu.txt"
so started looking , found snippet of code:
with open('menu.txt', 'r') f: # read entire file file1 # assuming 'file1.txt' relatively small... file1 = f.read() open('test.html', 'r') f: # assuming 'file2.txt' relatively small... file2 = f.read() # read file file2 # index() raise error if not found... f1_start = file1.index('<!--123-->') f1_end = file1.index('<!--321-->', f1_start) # '//end' after '//start' f2_start = file2.index('<!--123-->') f2_end = file2.index('<!--321-->', f2_start) # replace file2 lines proper file1 lines file2[f2_start:f2_end] = file1[f1_start:f1_end] open('test.html', 'w') f: f.write(file2)
and i've seen many examples using re
, replace
, such, nothing seems related need. anyway, right i'm trying on 1 file in same directory, when run on either linux machine or in windows python shell get:
traceback (most recent call last): file "p:\webpages\filereplace.py", line 18, in <module> file2[f2_start:f2_end] = file1[f1_start:f1_end] typeerror: 'str' object not support item assignment
i thought problem might've been with open
part, don't know.
in case contents of menu.txt beginning comment tag <!--123-->
, of <div id=menu>blah blah blah</div>
, end comment tag <!--321-->
. in html file, use same comment tags, , picture...
any suggestions?
most of time, when dealing in-place editing of files, turn fileinput
module:
import os import fileinput if __name__ == '__main__': # menu should not have marker, pure contents open('menu.txt') f: menu_contents = f.read() # initialize few items start_marker = '<!--123-->' end_marker = '<!--321-->' file_list = ['index.html', 'foo.html'] found_old_contents = false # loop replace text in place line in fileinput.input(file_list, inplace=true): line = line.rstrip() if line == start_marker: found_old_contents = true print line print menu_contents elif line == end_marker: found_old_contents = false if not found_old_contents: print line
discussion
the key here in function fileinput.input(file_list, inplace=true)
, takes list of file names, iterates through them line-by-line, , writes files whatever print
out.
you need come list of files (e.g. file_list
) means of os.walk()
or other methods.
i have tested code against 2 .html files , confident works. cannot guaranty results, nested directories. luck.
Comments
Post a Comment