문제

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.

도움이 되었습니까?

해결책

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).

다른 팁

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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top