Replace and inserting strings within .txt files with the use of regex

MRAB python at mrabarnett.plus.com
Tue Aug 10 11:12:02 EDT 2010


Νίκος wrote:
[snip]
> 
> The ID number of each php page was contained in the old php code
> within this string
> 
> PageID = some_number
> 
> So instead of create a new ID number for eaqch page i have to pull out
> this number to store to the beginnign to the file as comment line,
> because it has direct relationship with the mysql database as in
> tracking the number of each webpage and finding the counter of it.
> 
> # Grab the PageID contained within the php code and store it in id
> variable
> id = re.search( 'PageID = ', src_data )
> 
> How to tell Python to Grab that number after 'PageID = ' string and to
> store it in var id that a later use in the program?
> 
If the part of the file you're trying to match look like this:

     PageID = 12

then the regex should look like this:

     PageID = (\d+)

and the code should look like this:

     page_id = re.search(r'PageID = (\d+)', src_data).group(1)

The page_id will, of course, be a string.

> also i made another changewould something like this work:
> 
> ===============================
> # open same php file for storing modified data
> print ( 'writing to %s' % dest_f )
> f = open(src_f, 'w')
> f.write(src_data)
> f.close()
> 
> # rename edited .php file to .html extension
> dst_f = src_f.replace('.php', '.html')
> os.rename( src_f, dst_f )
> ===============================
> 
> Because instead of creating a new .html file and inserting the desired
> data of the old php thus having two files(old php, and new html) i
> decided to open the same php file for writing that data and then
> rename it to html.
> Would the above code work?

Why wouldn't it?



More information about the Python-list mailing list