Pergunta

I'm beginning to write a "parse" function to read maps for my engine/game, and I'm using the Tiled software to create the maps and export them to text files. Anyway, I decided to leave them as text to be easier for players to customize them, but I got curious. I was trying to replace all .txt file extensions to a new extension like ".sk" or whatever. Here's how I was trying to implement this:

import os, sys

def parse(map, path="Maps"):

    for f in os.listdir(path):
        try:
            print f
            os.rename(f,f.replace("txt","sk"))
        except WindowsError:
            print "Map file in use by another program."
            sys.exit()
    fullPath = os.path.join(path, map)
    m = open(fullPath, 'r+')
    return m.read()

print parse("map1.sk")

Problem is: I always get the "Map file in use by another program.". I want all .txt files in Maps folder to have their names replaced to .sk (Or whatever) files.

Foi útil?

Solução

If you change the

    ...
    except WindowsError:
        print "Map file in use by another program."
        sys.exit()
    ...

with

    ...
    except OSError as e:
        print(e)
        sys.exit()
    ...

You will see something like this:

[Errno 2] No such file or directory: 'map1.sk'

Because you map file is in Maps Directory and you are trying to renamte it like it is in your current directory.

This will do the job:

import os, sys

def parse(path="Maps/"):

    for f in os.listdir(path):
        try:
        os.rename(path+f,path+f.replace("txt","sk"))
        except OSError as e:
            print(e)
            sys.exit()

parse()

I used OSError instead of WindowsError because WindowsError is only available for windows user (not sure but seems like its true).

Outras dicas

You need to change your working directory to that path to change file names.

Try this:

def parse(map, path="Maps"):
    new_path = os.path.join(os.getcwd(), path)
    os.chdir(new_path)
    for f in os.listdir(new_path):
        try:
            print f
            os.rename(f,f.replace("txt","sk"))
        except WindowsError:
            print "Map file in use by another program."
            sys.exit()

Also you might want to use str.endswith(".txt") if your file extensions are not hidden.

You could try this:

def parse(map, path="Maps"):
    for f in os.listdir(path):
        try:
            print(f)
            os.rename(
                path + f,
                os.path.splitext(f)[0] + ".sk"
                )
            )
        except OSError:
            print("Map file in use by another program.")
            sys.exit()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top