Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当用户运行脚本时,如何在Python中写入文本文件?_Python_Python 2.7 - Fatal编程技术网

当用户运行脚本时,如何在Python中写入文本文件?

当用户运行脚本时,如何在Python中写入文本文件?,python,python-2.7,Python,Python 2.7,作为学习练习的一部分,我创建了一个基本的游戏,我想在学习更多Python时对其进行扩展。这个游戏是一个非常基本的,基于文本的冒险游戏,一些房间可以让用户挑选物品 我想在用户玩游戏时将这些项目写入一个文本文件,然后给用户一个选项,在游戏期间检查他/她的“库存”。我无法获得使脚本能够执行以下操作的正确语法: 当用户开始游戏时创建一个新的文本文件 当用户到达游戏的该部分时,将定义的项目写入文本文件 创建一个查看清单的选项(我有一个方法) 下面是脚本的一部分示例,其中我尝试了注释掉的代码: def

作为学习练习的一部分,我创建了一个基本的游戏,我想在学习更多Python时对其进行扩展。这个游戏是一个非常基本的,基于文本的冒险游戏,一些房间可以让用户挑选物品

我想在用户玩游戏时将这些项目写入一个文本文件,然后给用户一个选项,在游戏期间检查他/她的“库存”。我无法获得使脚本能够执行以下操作的正确语法:

  • 当用户开始游戏时创建一个新的文本文件
  • 当用户到达游戏的该部分时,将定义的项目写入文本文件
  • 创建一个查看清单的选项(我有一个方法)
下面是脚本的一部分示例,其中我尝试了注释掉的代码:

def room1_creep():
print "You slowly enter the room, and look around. In the opposite corner of the room, you see a ferocious looking bear. It doesn't seem to have seen you yet."
print "You make your way to the chest at the end of the room, checking to see whether the bear has seen you yet. So far, so good."
print "Just as you reach the treasure chest, you hear a roar from the bear that seems to have seen you. What do you do? Rush 'back' to the door or go for the 'treasure'?"

creep_choice = raw_input("You have two choices: 'back' or 'treasure'. > ")

if creep_choice == "back":
    print "You make a run for it. You feel the bear's hot breath on the back of your neck but you reach the door before it catches you."
    print "You slam the door closed behind you and you find yourself back in the passage."
    return entrance()
elif creep_choice == "treasure":
    print "You manage to grab a few handfuls of gold coins before the bear stabs its claws into you and sprint for the exit."
    # inv = open("ex36_game_txt.txt", 'w')
    # line3 = raw_input("10 gold coins")
    # inv.write(line3)
    # inv.write("\n")
    # inv.close()
    # I also want to add "gold coins" to a text file inventory that the script will add to.
    print "You manage to slam the door closed just as the bear reaches it. It howls in frustration and hunger."
    return middle()
else:
    room1_indecision()
如果完整的脚本将是有用的。我在这里进行了几次搜索,最接近我认为我需要的问题是。我不知道如何有效地实施这一点


我面临的一个主要挑战是如何让脚本动态创建一个新的文本文件,然后用清单中的项目填充该文本文件。

如果需要用python编写文件,请使用
和open(…)

打开时
将自动处理异常,并在您完成写入时关闭文件

如果需要创建已定义项的列表,可以初始化字典并将其保存在内存中,如下所示:

list_of_items = {item0: "...", item1: "...", ...}
在单独的模块中定义它,并在需要时导入它。然后,您可以通过键访问其值,并在游戏期间将其写入库存

我不确定您创建查看和清点选项的确切含义。为什么不像以前那样使用
raw_input()
,并检查word
库存

options = ('1. Inventory.\n'
           '2. Save.\n'
           '3. Exit.\n')

option = raw_input("Choose an option: {}".format(options))

if option == "Inventory":

    with open("ex36_game_txt.txt", "r") as inv:
        for item in inv:
            print(inv)
它将打印出您的库存文件的内容


另外请注意,如果您计划在python3中运行游戏,则不要使用
raw\u input()
,而是使用
input()

如果使用它保证类始终返回其自身的唯一实例,则无需写入文本文件。因此,您可以创建一个名为“PlayerInventory”的类,一旦它被实例化至少一次,无论何时何地在代码中尝试实例化库存类,它都将返回相同的实例

如果您希望使库存持久化,以便玩家可以保存游戏并在关闭程序后取回库存,请在退出时使用名为“pickle”的模块直接序列化库存对象


示例:

class PlayerInventory(object):

    _instance = None

    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
             class_._instance = object.__new__(class_, *args, **kwargs)
             # you need to initialize your attributes here otherwise they will be erased everytime you get your singleton
             class_._instance.gold_coins = 0
             class_._instance.magic_items = []
             # etc... whatever stuff you need to store !
        return class_._instance
您可以在单独的文件中编写此类,并在需要访问库存时将其导入。示例用例(假设您在名为“inventory.py”的文件中编写了该类,该文件包含在名为“mygame”的主包中):

在代码中的其他地方,您可能需要检查玩家是否有足够的金币来执行特定操作:

from mygame.inventory import PlayerInventory

if PlayerInventory().gold_coins < 50:

    print "Unfortunately, you do not possess enough wealth for this action..."

else:
    # Whatever you wish ...

请注意,如果将导入行放在最前面,则每个文件只需要导入一次

你说的我不太明白,但据我所知,这似乎是一种有趣的替代方法。谢谢。是的,我知道如果你是作为一个学习练习来做的,并且不一定对面向对象编程了解很多,这可能会让人困惑!我将添加一个示例来说明这个概念。我已经查看了您的github repo,作为一个友好的avice,我建议将您的代码拆分为多个源文件,这将有助于构建和维护它!祝你的游戏好运,开始学习python看起来是个好主意!谢谢你的建议。一旦我知道如何做到这一点,并使所有的工作一起进行,我会这样做。太好了,谢谢你。这很有帮助。我是否需要执行脚本并从命令行命名文本文件,或者脚本是否只创建一个名为
with open()
?@PaulJacobson如果文件不存在,
with open()
将在使用参数
w
时自动创建它。如果它存在,文件将被重写。如果要附加到现有文件,则需要使用选项
a
from mygame.inventory import PlayerInventory

# Adding coins to inventory
if has_won_some_gold:
    PlayerInventory().gold_coins += 10
from mygame.inventory import PlayerInventory

if PlayerInventory().gold_coins < 50:

    print "Unfortunately, you do not possess enough wealth for this action..."

else:
    # Whatever you wish ...
from mygame.inventory import PlayerInventory

if player_picked_up_sword:
    print "Got: 1 bastard sword"
    PlayerInventory().magic_items.append("bastard sword")