473,703 Members | 2,543 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String find and replace

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

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

Traceback (most recent call last):
File "html_find_repl ace.py", line 12, in ?
find_replace(se tpath)
File "html_find_repl ace.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 33673

"hokieghal9 9" <ho********@hot mail.com> wrote in message
news:bi******** **@solaris.cc.v t.edu...
import os, string
print " "
setpath = raw_input("Ente r the path: ")
def find_replace(se tpath):
for root, dirs, files in os.walk(setpath ):
fname = files
for fname in files:
find = string.find(fil e(os.path.join( root,fname),
'rb').read(), 'THIS')
print find
if find >=1:
replace = string.replace( str, 'THIS', 'THAT')
find_replace(se tpath)
print " "

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

Traceback (most recent call last):
File "html_find_repl ace.py", line 12, in ?
find_replace(se tpath)
File "html_find_repl ace.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("Ente r the path: ")
def find_replace(se tpath):
for root, dirs, files in os.walk(setpath ):
fname = files
for fname in files:
find = string.find(fil e(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(se tpath)
print " "

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

Traceback (most recent call last):
File "html_find_repl ace.py", line 12, in ?
find_replace(se tpath)
File "html_find_repl ace.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("Ente r the path: ")
for root, dirs, files in os.walk(setpath ):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.jo in(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mys tr, 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********@hot mail.com):
import os, string
print " "
setpath = raw_input("Ente r the path: ")
def find_replace(se tpath):
for root, dirs, files in os.walk(setpath ):
fname = files
for fname in files:
find = string.find(fil e(os.path.join( root,fname), 'rb').read(), 'THIS')


^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
this string is never bound to a name
(ie, you never assign str=file(...).r ead())
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.jo in(root,fname), 'rb')
mystr = myfile.read()
myfile.close()
find = string.find(mys tr, '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("Ente r the path: ")
for root, dirs, files in os.walk(setpath ):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.jo in(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mys tr, 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********@hot mail.com):
import os, string
print " "
setpath = raw_input("Ente r the path: ")
def find_replace(se tpath):
for root, dirs, files in os.walk(setpath ):
fname = files
for fname in files:
find = string.find(fil e(os.path.join( root,fname), 'rb').read(),
'THIS')
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ this string is never bound to a name
(ie, you never assign str=file(...).r ead())
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.jo in(root,fname), 'rb')
mystr = myfile.read()
myfile.close()
find = string.find(mys tr, '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********@hot mail.com> wrote in message
news:3F******** ****@hotmail.co m...
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(th is, that)
outputFile = file(filename, 'w')
outputFile.writ e(data)
outputFile.clos e()

--
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(th is, that)
outputFile = file(filename, 'w')
outputFile.writ e(data)
outputFile.clos e()

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

import os, string
setpath = raw_input("Ente r the path: ")
for root, dirs, files in os.walk(setpath ):
fname = files
x = 'THIS'
y = 'THAT'
for fname in files:
myfile = file(os.path.jo in(root,fname), 'r')
mystr = myfile.read()
myfile.close()
search = string.find(mys tr, 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

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

Similar topics

5
7309
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 = s.find(foo, i)) { s.replace(i, foo.size(), bar);
32
14853
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 ((someString.IndexOf("something1",0) >= 0) || ((someString.IndexOf("something2",0) >= 0) ||
0
3079
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 want to replace all of them. You need to look at it in a case-by-case basis. What can you do? Answer: emacs.
16
1589
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 browser i've built). I'm trying to simply remove the root string from the path string, so for example below: root = E:\Web\Websites\fileBrowse\ path = E:\Web\Websites\fileBrowse\images\
5
5478
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> /*------------------------------------------------------------------------------------------- | Function name : strrep
15
50250
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
7958
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
2799
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 find a chosen substring lets say "cat" and then replace it with a difrent inputed substring say "dog". Tried to get as far as i could on my own but need some help, sugestions, snippets or guidence. # include<stdio.h> # include<math.h> #...
2
2487
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 replaced, i can't make a buffer -- hence i thought of using malloc() -- is what i have below effective? it doesn't seem to work though - the returned string just returns the substituted part. Any thoughts / comments are welcomed.
0
8750
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9112
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9005
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4425
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4680
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2440
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2058
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.