Python 覆盖我的文件并且找不到其他文件

标签 python file python-2.7

所以我正在用 Python 制作一个游戏,为了保存,有玩家保存和自动保存。如果我尝试打开播放器保存它会显示类似 [Errno 2] No such file or directory: 'C:/Program Files (x86)/Legendary Forging/test.ini' 我可以转到然而,Windows 资源管理器并打开该目录。

当我打开自动保存文件时,它会替换掉其中的任何内容。 (我之前期间和之后在程序外打开文件进行检查)

这是我的代码:

import os
from random import randint
import time
import threading

class Engine(object):
    loop_condition = True
    def __init__(self, scene_map):
        self.scene_map = scene_map
    def play(self):
        with open("C:\\Program Files (x86)\\Legendary Forging\\autosave.ini", 'w') as player_save:
            player_save.close()
        current_scene = self.scene_map.opening_scene()
        while self.loop_condition:
            print "\n--------"
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)
            auto_save("")
            if next_scene_name == 'none':
                print
                self.loop_condition == False

class Player(object):
    hp = 100
    mana = 100
    exp = 0
    lvl = 1
    inventory = {}
    equipped = {}
    strength = 0
    intelligence = 0
    wisdom = 0
    dexterity = 0
    location = ""
    role = ""
    name = ""

class Commands(object):
    def determine(self, command):
        self.command = command
        help_word=""
        if command[0:4] == "exit":
            print
            time.sleep(.5)
            os._exit(1)
        elif command[0:4] == "save":
            create_save(command[4:])
            print "Your game has been saved under the name: %s" % command[4:]
        elif command[0:5] == "dance":
            print
            print "You dance in joy"
        elif command[0:4] == "help":
            for x in command[4:]:
                if x == " ":
                    del x
                else:
                    help_word += x
            if help_word == "warrior":
                print "\nwarrior description"
            elif help_word == "wizard":
                print "\nwizard description"
            elif help_word == "rogue":
                print "\nrogue description"
            elif help_word == "cleric":
                print "\ncleric description"
            else:
                print "There is no help file under that name."
        elif Player.location == 'startroom':
            if command[0:7] == "warrior":
                print
                print "You have chosen to be the Warrior."
                Player.strength +=10
                Player.wisdom +=2
                Player.dexterity +=6
                Player.hp +=20
                Player.intelligence +=0
                Player.mana += -100
                Player.role = "warrior"
            elif command[0:6] == "wizard":
                print
                print "You have chosen to be the Wizard."
                Player.strength +=0
                Player.wisdom +=6
                Player.intelligence +=10
                Player.dexterity +=2
                Player.hp += -20
                Player.mana +=50
                Player.role = "wizard"
            elif command[0:5] == "rogue":
                print
                print "You have chosen to be the Rogue."
                Player.strength +=4
                Player.wisdom +=4
                Player.intelligence +=2
                Player.dexterity +=10
                Player.hp +=0
                Player.mana +=-50
                Player.role = "rogue"
            elif command[0:6] == "cleric":
                print
                print "You have chosen to be the Cleric."
                Player.strength +=6
                Player.wisdom +=10
                Player.dexterity +=6
                Player.hp +=10
                Player.intelligence +=0
                Player.mana += 0
                Player.role = "cleric"
            elif command[0:4] == "load":
                if command[5:] == "autosave":
                    open_save("autosave")
                    print "Loaded autosave."
                else:
                    open_save(command[5:].lower())
                    print "Loaded save name: %s" % command [5:]

class Scene(object):
    def enter(self):
        print "Scene info"

class StartRoom(Scene):
    role_list = ["Warrior", "Rogue", "Wizard", "Cleric"]
    def enter(self):
        Player.location = "startroom"
        print "To load a previous games auto-save, type 'load autosave'\nTo load a custom save type 'load <save name>" 
        choice_load = raw_input(">")
        command_load = Commands()
        command_load.determine(choice_load)
        if Player.location != "startroom":
            return Player.location
        print"Welcome! What is your name?"
        choice_name = raw_input(">")
        self.choice_name = choice_name
        print "Choose one of the following roles."
        print "Type \"Help <role>\" to see more info about each role."
        print
        for x in self.role_list:
            print x
        print
        choice_role = raw_input(">")
        self.choice_role = choice_role.lower()
        Player.name = self.choice_name
        Player.role = self.choice_role
        command_room1 = Commands()
        command_room1.determine(self.choice_role) 
        if self.choice_role == "warrior" or self.choice_role == "wizard" or self.choice_role == "rogue" or self.choice_role == "cleric":
            time.sleep(.5)
            return "room1"
        else:
            return 'startroom'

class Death(Scene):
    quips = [
             "Wow. Much Death, so sad. Wow.",
             "Hah you suck at this!",
             "Try Again!",
             ]
    def enter(self):
        Player.location = "death"
        print Death.quips[randint(0, len(self.quips)-1)]
        print
        print "Game Over"
        return 'none'

class Room1(Scene):
    def enter(self):
        Player.location = "room1"
        print "Room 1"
        choice_i = raw_input("\n >")
        choice=choice_i.lower()
        self.choice = choice
        if self.choice == "left" or self.choice == "l":
            return "death"
        elif self.choice == "right" or self.choice == "r":
            return "room2"
        else:
            command_room1 = Commands()
            command_room1.determine(self.choice) 
            time.sleep(.5)
            return "room1"

class Room2(Scene):
    def enter(self):
        Player.location = "room2"
        print "Room 2"

class Map(object):
    scenes = {
        'room1': Room1(),
        'death': Death(),
        'room2': Room2(),
        'startroom': StartRoom()
    }
    def __init__(self, start_scene):
        self.start_scene = start_scene
    def next_scene(self, scene_name):
        return Map.scenes.get(scene_name)
        Player.location = Map.scenes.get(scene_name)
    def opening_scene(self):
        return self.next_scene(self.start_scene)

class Saving(object):
    savepath = "C:\\Program Files (x86)\\Legendary Forging"
    global auto_save
    global open_save
    global create_save
    def create_dir(self):
        if os.path.exists("C:\\Program Files (x86)\\Legendary Forging") == False:
           os.makedirs("C:\\Program Files (x86)\\Legendary Forging")
    def create_save(save_name):
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (save_name), 'w') as player_save:
            player_save.close()
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (save_name), 'r+') as player_save:
            player_save.write(    #not sure how to do inventory or equipped yet
"""player.name = %s
player.role = %s
player.hp = %d
player.mana = %d
player.exp = %d
player.lvl = %d
strength = %d
intelligence = %d
wisdom = %d
dexterity = %d
location = %s""" % (Player.name, Player.role, Player.hp, Player.mana, Player.exp, Player.lvl, Player.strength, Player.intelligence, Player.wisdom, Player.dexterity, Player.location))
            player_save.close()
    def auto_save(self):
            with open("C:/Program Files (x86)/Legendary Forging/autosave.ini", 'w') as player_save:
                player_save.write(    #not sure how to do inventory or equipped yet
"""player.name = %s
player.role = %s,
player.hp = %d,
player.mana = %d,
player.exp = %d,
player.lvl = %d,
strength = %d,
intelligence = %d,
wisdom = %d,
dexterity = %d,
location = %s,""" % (Player.name, Player.role, Player.hp, Player.mana, Player.exp, Player.lvl, Player.strength, Player.intelligence, Player.wisdom, Player.dexterity, Player.location))
    def open_save(file_name):
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (file_name),"r") as player_save:
            print player_save.read
            player_save.close()

a_map = Map('startroom')
a_game = Engine(a_map)
a_save = Saving()
a_save.create_dir()
a_game.play()

我不确定为什么会这样做,因为今天早上它工作正常。我认为在我将保存文件名的输入更改为全部小写后,它发生了变化。

编辑 我发现我在 print player_save.read 之后忘记了一对括号 不过,除了自动保存文件之外,我仍然无法加载任何其他文件

编辑我找到了它无法加载的原因!

elif command[0:4] == "save":
            create_save(command[4:])

4 应该是 5,它占用了加载和文件名之间的空格。

最佳答案

with open("C:\\Program Files (x86)\\Legendary Forging\\autosave.ini", 'w') as player_save:
    player_save.close()

我不确定您认为这段代码在做什么,但它的作用是以覆盖模式打开文件(删除现有内容),然后立即将其关闭。我只是简单地浏览了你的代码,但是每次游戏开始时都这样做,这似乎不是你想要做的事情?

关于Python 覆盖我的文件并且找不到其他文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19884857/

相关文章:

python - 使用 7zip 和 python 在给定路径中创建受密码保护的文件

python - 更改后重新加载模块

python - numpy 仅对非零部分执行函数,同时保留数组结构

java - 在尚未完成复制/上传时读取文件内容

Java读取文本文件并搜索一行

java - Java中如何播放声音文件

python - 如何使用 Python + Selenium 设置代理身份验证(用户和密码)

python - python 的递归代码检查器

Python Pandas Groupby 删除日期时间列

python - 加权斜率一种算法? (从 Python 移植到 R)