0

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?

3
  • You cannot write to a file when it's opened for reading (r+). If you'd have opened it with w, you could file.write(replaced_contents)... Commented Apr 24, 2014 at 12:41
  • Are you trying to write this back into the file or are you trying to just print it out? Commented Apr 24, 2014 at 12:44
  • The error message states that the write function takes 1 argument but 0 has been given. As per the python documentation , the format for file writing function is f.write(string) writes the contents of string to the file, returning None Commented Apr 24, 2014 at 12:48

2 Answers 2

2

I think you mean to use file.read() rather than file.write()

Sign up to request clarification or add additional context in comments.

3 Comments

It depends on whether he wants to read it out with the replacement or if he want's to actually replace the file - the print statement could just be debugging
@Scironic Unless there is some nicely idiomatic python way to apply a function to lines in a file, he is going to have to read it in at that point. He may well need to add a write call as well, but that would have to go after the replace call.
you're right of course - I should have phrased myself better. I was trying to point out that that, whilst this would be an issue, it may not be the main issue which he is interested in. I was getting ahead of myself in that comment.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.