472,371 Members | 1,394 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

String find and replace

import os, string
print " "
setpath = raw_input("Enter the path: ")
def find_replace(setpath):
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
find = string.find(file(os.path.join(root,fname),
'rb').read(), 'THIS')
print find
if find >=1:
replace = string.replace(str, 'THIS', 'THAT')
find_replace(setpath)
print " "

Why doesn't this work? I get this error:

Traceback (most recent call last):
File "html_find_replace.py", line 12, in ?
find_replace(setpath)
File "html_find_replace.py", line 11, in find_replace
replace = string.replace(str, 'THIS', 'THAT')
File "/usr/local/lib/python2.3/string.py", line 370, in replace
return s.replace(old, new, maxsplit)
TypeError: expected a character buffer object

Jul 18 '05 #1
10 33501

"hokieghal99" <ho********@hotmail.com> wrote in message
news:bi**********@solaris.cc.vt.edu...
import os, string
print " "
setpath = raw_input("Enter the path: ")
def find_replace(setpath):
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
find = string.find(file(os.path.join(root,fname),
'rb').read(), 'THIS')
print find
if find >=1:
replace = string.replace(str, 'THIS', 'THAT')
find_replace(setpath)
print " "

Why doesn't this work? I get this error:

Traceback (most recent call last):
File "html_find_replace.py", line 12, in ?
find_replace(setpath)
File "html_find_replace.py", line 11, in find_replace
replace = string.replace(str, 'THIS', 'THAT')
File "/usr/local/lib/python2.3/string.py", line 370, in replace
return s.replace(old, new, maxsplit)
TypeError: expected a character buffer object
what's "str" in line 11?

John Roth

Jul 18 '05 #2
hokieghal99 wrote:
import os, string
print " "
setpath = raw_input("Enter the path: ")
def find_replace(setpath):
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
find = string.find(file(os.path.join(root,fname), 'rb').read(),
'THIS')
print find
if find >=1:
replace = string.replace(str, 'THIS', 'THAT') ^^^

In your app, what do you think 'str' is?

You haven't defined it, but it still exists. It's the string type, *not*
a particular string (cos you haven't defined it). That's why you get the
error below:
find_replace(setpath)
print " "

Why doesn't this work? I get this error:

Traceback (most recent call last):
File "html_find_replace.py", line 12, in ?
find_replace(setpath)
File "html_find_replace.py", line 11, in find_replace
replace = string.replace(str, 'THIS', 'THAT')
File "/usr/local/lib/python2.3/string.py", line 370, in replace
return s.replace(old, new, maxsplit)
TypeError: expected a character buffer object


-- Gerhard

Jul 18 '05 #3
Thanks for the explanation, I can make it work this way:

import os, string
setpath = raw_input("Enter the path: ")
for root, dirs, files in os.walk(setpath):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.join(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mystr, x)
if search >=1:
string.replace(mystr, x, y)
print "Replacing", x, "with", y, "in", fname

If only I could actually make the change to the files! It works in
theory, but not in practice ;) Anyone recommend how to actual write the
change to the file? I'm new to this, so be kind.

Thanks Everyone!!!

Geoff Gerrietts wrote:
Quoting hokieghal99 (ho********@hotmail.com):
import os, string
print " "
setpath = raw_input("Enter the path: ")
def find_replace(setpath):
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
find = string.find(file(os.path.join(root,fname), 'rb').read(), 'THIS')


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
this string is never bound to a name
(ie, you never assign str=file(...).read())
print find
if find >=1:
replace = string.replace(str, 'THIS', 'THAT')


^^^
this name is currently bound to
the builtin function str()

find_replace(setpath)
print " "


You might consider the fragment below, instead. It's a couple lines
longer, but safer (your .close() happens exactly when you want it to)
and probably more readable.

for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
myfile = file(os.path.join(root,fname), 'rb')
mystr = myfile.read()
myfile.close()
find = string.find(mystr, 'THIS')
print find
if find >=1:
replace = string.replace(mystr, 'THIS', 'THAT')
Luck,
--G.

Jul 18 '05 #4

"hokiegal99" <ho********@vt.edu> wrote in message
news:3F**************@vt.edu...
Thanks for the explanation, I can make it work this way:

import os, string
setpath = raw_input("Enter the path: ")
for root, dirs, files in os.walk(setpath):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.join(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mystr, x)
if search >=1:
string.replace(mystr, x, y)
print "Replacing", x, "with", y, "in", fname

If only I could actually make the change to the files! It works in
theory, but not in practice ;) Anyone recommend how to actual write the
change to the file? I'm new to this, so be kind.
Are you trying to rename the file? Look under os - Files and Directories
for the rename() function. It's 6.1.4 in the 2.2.3 docs.

John Roth
Thanks Everyone!!!

Geoff Gerrietts wrote:
Quoting hokieghal99 (ho********@hotmail.com):
import os, string
print " "
setpath = raw_input("Enter the path: ")
def find_replace(setpath):
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
find = string.find(file(os.path.join(root,fname), 'rb').read(),
'THIS')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this string is never bound to a name
(ie, you never assign str=file(...).read())
print find
if find >=1:
replace = string.replace(str, 'THIS', 'THAT')


^^^
this name is currently bound to
the builtin function str()

find_replace(setpath)
print " "


You might consider the fragment below, instead. It's a couple lines
longer, but safer (your .close() happens exactly when you want it to)
and probably more readable.

for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
myfile = file(os.path.join(root,fname), 'rb')
mystr = myfile.read()
myfile.close()
find = string.find(mystr, 'THIS')
print find
if find >=1:
replace = string.replace(mystr, 'THIS', 'THAT')
Luck,
--G.


Jul 18 '05 #5
John Roth wrote:
Are you trying to rename the file? Look under os - Files and Directories
for the rename() function. It's 6.1.4 in the 2.2.3 docs.

John Roth


No, I'm trying to find 'this' in files and replace it with 'that'
recursively through a directory. It works, but it doesn't actually
commit the change to the files, it finds 'this' and reports that it
replaced it with 'that', but when I run the scipt again it reports the
same files that it just fixed.

Jul 18 '05 #6

"hokiegal99" <ho********@hotmail.com> wrote in message
news:3F************@hotmail.com...
John Roth wrote:
Are you trying to rename the file? Look under os - Files and Directories
for the rename() function. It's 6.1.4 in the 2.2.3 docs.

John Roth
No, I'm trying to find 'this' in files and replace it with 'that'
recursively through a directory. It works, but it doesn't actually
commit the change to the files, it finds 'this' and reports that it
replaced it with 'that', but when I run the scipt again it reports the
same files that it just fixed.


Oh. You need to open it again for write and write the
changed string back out. The string doesn't have any
persistant connection to the file.

John Roth

Jul 18 '05 #7
hokiegal99 wrote:
I hate to answer my own post, but I think I understand what I'm doing
wrong. I'm finding and replacing 'this' with 'that' in the varible
named
mystr, not the actual files. So, how would I go about making the
change
to the actual files instead of a variable that contains their content?


Easy:

inputFile = file(filename, 'r')
data = inputFile.read()
inputFile.close()
data = data.replace(this, that)
outputFile = file(filename, 'w')
outputFile.write(data)
outputFile.close()

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ There never was a good war or a bad peace.
\__/ Benjamin Franklin
Jul 18 '05 #8
Easy for you maybe ;)

That works great. I learn something each time I post to the list. With a
community like this, Python will be around forever!!! Thanks for the help.

Erik Max Francis wrote:
hokiegal99 wrote:

I hate to answer my own post, but I think I understand what I'm doing
wrong. I'm finding and replacing 'this' with 'that' in the varible
named
mystr, not the actual files. So, how would I go about making the
change
to the actual files instead of a variable that contains their content?

Easy:

inputFile = file(filename, 'r')
data = inputFile.read()
inputFile.close()
data = data.replace(this, that)
outputFile = file(filename, 'w')
outputFile.write(data)
outputFile.close()

Jul 18 '05 #9
hokiegal99 wrote:
Thanks for the explanation, I can make it work this way:

import os, string
setpath = raw_input("Enter the path: ")
for root, dirs, files in os.walk(setpath):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.join(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mystr, x)
if search >=1:
string.replace(mystr, x, y)
print "Replacing", x, "with", y, "in", fname

If only I could actually make the change to the files! It works in
theory, but not in practice ;) Anyone recommend how to actual write the
change to the file? I'm new to this, so be kind.


I once wrote a replace recursive script. Maybe it helps you:
http://www.thomas-guettler.de/script...cursive.py.txt

thomas


Jul 18 '05 #10
Thomas Güttler wrote:
I once wrote a replace recursive script. Maybe it helps you:
http://www.thomas-guettler.de/script...cursive.py.txt

thomas


Yes that's very helpful, but a bit too complex for me at this point in
time. Here is the script that I put together from all of the responses I
recieved from the list:

#Thanks to comp.lang.python
import os, string
print " "
print "************************************************* *****"
print " Three Easy Steps to a Recursive find and Replace "
print "************************************************* *****"
print " "
x = raw_input("1. Enter the string that you'd like to find: ")
print " "
y = raw_input("2. What would you like to replace %s with: " %x)
print " "
setpath = raw_input("3. Enter the path where the prgroam should run: ")
print " "
for root, dirs, files in os.walk(setpath):
fname = files
for fname in files:
inputFile = file(os.path.join(root,fname), 'r')
data = inputFile.read()
inputFile.close()
search = string.find(data, x)
if search >=1:
data = data.replace(x, y)
outputFile = file(os.path.join(root,fname), 'w')
outputFile.write(data)
outputFile.close()
print "Replacing", x, "with", y, "in", fname
print " "
print "**********"
print " Done "
print "**********"
print " "

Jul 18 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: mr h q | last post by:
Hi all, i want to replace $ to \$ so linux can work with paths and filenames that contain $. I wrote the following code for(string::size_type i = s.find(exist, 0); i != string::npos; i =...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
0
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not...
16
by: ^MisterJingo^ | last post by:
Hi all, I have a variable called root which contains (E:\Web\Websites\fileBrowse\) and then I have a variable called path which uses root, and adds directories on to it (this is part of a file...
5
by: int main(void) | last post by:
Hi all, Following is my attempt to write a string search and replace function. #include <stdio.h> #include <stdlib.h> #include <string.h>...
15
by: morleyc | last post by:
Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris
7
by: silverburgh.meryl | last post by:
Hi, If I have a string like this: char buff; buff ='h'; buff ='e'; buff ='l'; buff ='l'; buff ='o';
4
by: sandvet03 | last post by:
I am trying to expand on a earlier program for counting subs and now i am trying to replace substrings within a given string. For example if the main string was "The cat in the hat" i am trying to...
2
by: kevin.eugene08 | last post by:
hi all, i'm trying to replace a string with known "tokens" with values -- and am not sure how to do this effectively. Since i don't know the size of the string containing the tokens to be...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.