I would like to search for a specific keyword across multiple files in a folder. If the keyword is found I would like the word to be replaced by another given word. If that operation takes place output the file name that the word was found and replaced. I would like this to be done in python and I am not sure how to do it. The files can be txt or any file extensions that can be opened by notepad and read.
Asked
Active
Viewed 540 times
-3
-
3As written, this could be done in any language... If you have a `python` question, please [edit] your post to include what you've tried so far and mention what issues you're having - http://idownvotedbecau.se/noattempt/ – OneCricketeer Jun 28 '21 at 14:49
-
Okay ill update with what i have so far. Thank you for your suggestion – Rafi Hasan Jun 28 '21 at 15:04
1 Answers
1
is this what you're looking for
# only searches in current directory files
# replace os.getcwd() by directory path of what you want to search or use a variable
import os
keyword = input("Enter Keyword to search : ")
replacement = input("Enter replacement string : ")
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
content = f.read()
if keyword in content:
with open(os.path.join(os.getcwd(), filename), 'w') as fw: # open in write mode
writecontent = content.replace(keyword, replacement)
fw.write(writecontent)
print(f"Keyword {keyword} found and replaced in file : {filename}")

Kapil
- 165
- 1
- 9
-
Hey thank you for posting this. This is along the lines of what I am looking for but when i run the script it gives me PermissionError: [Errno 13]. Do you know any reason why? – Rafi Hasan Jun 28 '21 at 15:57
-
@RafiHasan check these out [https://stackoverflow.com/a/62244490/12785964](https://stackoverflow.com/a/62244490/12785964) and [https://stackoverflow.com/q/13207450/12785964](https://stackoverflow.com/q/13207450/12785964) and similar questions – Kapil Jun 29 '21 at 06:56