1

I'm trying to go through a bunch of files in a directory and find and replace a list of strings and write them to the same file. When I run the scripts all the files in the directory turn out blank! What am I doing wrong here?

os.chdir("Resources/maps_sideScrolling/HD")

replacements = {'tilewidth=\"16\"':'tilewidth=\"32\"', 'tileheight=\"16\"':'tileheight=\"32\"', '.png':'-hd.png'}

for files in os.listdir("."):
    if files.endswith("-hd.tmx"):
        fo = open(files, "rU")
        fw = open(files, "w")

        for line in fo:
            for src, target in replacements.iteritems():
                line = line.replace(src, target)
            fw.write(line)

        fo.close();
        fw.close();

1 Answer 1

2

If you want to overwrite the file you can use below code:

os.chdir("Resources/maps_sideScrolling/HD")
replacements = {'tilewidth=\"16\"':'tilewidth=\"32\"', 'tileheight=\"16\"':'tileheight=\"32\"', '.png':'-hd.png'}

for files in os.listdir("."):
    if files.endswith("-hd.tmx"):
        fo = open(files, "rU+")
        text = fo.read()
        for src, target in replacements.iteritems():
                text = text.replace(src, target)
        fo.seek(0)
        fo.write(text)
        fo.truncate()
        fo.close()
Sign up to request clarification or add additional context in comments.

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.