Replace and inserting strings within .txt files with the use of regex
Νίκος
nikos.the.gr33k at gmail.com
Mon Aug 9 03:07:22 EDT 2010
Now the code looks as follows:
=============================
#!/usr/bin/python
import re, os, sys
id = 0 # unique page_id
for currdir, files, dirs in os.walk('test'):
for f in files:
if f.endswith('php'):
# get abs path to filename
src_f = join(currdir, f)
# open php src file
print ( 'reading from %s' % src_f )
f = open(src_f, 'r')
src_data = f.read() # read contents of PHP file
f.close()
# replace tags
print ( 'replacing php tags and contents within' )
src_data = re.sub( '<?(.*?)?>', '', src_data )
# add ID
print ( 'adding unique page_id' )
src_data = ( '<!-- %d -->' % id ) + src_data
id += 1
# add template variables
print ( 'adding counter template variable' )
src_data = src_data.replace('</body>', '<br><br><center><h4><font
color=green> Αριθμός Επισκεπτών: %(counter)d </body>' )
# rename old php file to new with .html extension
src_file = src_file.replace('.php', '.html')
# open newly created html file for inserting data
print ( 'writing to %s' % dest_f )
dest_f = open(src_f, 'w')
dest_f.write(src_data) # write contents
dest_f.close()
I just tried to test it. I created a folder names 'test' in me 'd:\'
drive.
Then i have put to .php files inside form the original to test if it
would work ok for those too files before acting in the whole copy and
after in the original project.
so i opened a 'cli' form my Win7 and tried
D:\>convert.py
D:\>
Itsjust printed an empty line and nothign else. Why didn't even try to
open the folder and fiels within?
Syntactically it doesnt ghive me an error!
Somehting with os.walk() methos perhaps?
More information about the Python-list
mailing list