Reputation: 15
So I need to find all files with certain extension in this case .txt
. Then I must open all these files and change certain string with another string... and here i'm stuck.
here is my code:
import os, os.path
find_files=[]
for root, dirs, files in os.walk("C:\\Users\\Kevin\\Desktop\\python programi"):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
find_files.append(fullpath)
for i in find_files:
file = open(i,'r+')
contents = file.write()
replaced_contents = contents.replace('xy', 'djla')
print i
ERROR mesage:
line 12, in <module>
contents = file.write()
TypeError: function takes exactly 1 argument (0 given)
i know that there is misssing an argument but which argument should I use?
i think it would be better if i change the code from for i in find files:
down
any advice?
Upvotes: 0
Views: 110
Reputation: 4086
Not sure if you're just trying to print out the changes or if you want to actually rewrite them into the file, in which case you could just do this:
for i in find_files:
replaced_contents = ""
contents = ""
with open(i, "r") as file:
contents = file.read()
replaced_contents = contents.replace('xy', 'djla')
with open(i, "w") as file:
file.write(replaced_contents)
print i
Upvotes: 0
Reputation: 7813
I think you mean to use file.read()
rather than file.write()
Upvotes: 2