【问题标题】:How can I write to a text file in Python while a user is running a script?当用户运行脚本时,如何在 Python 中写入文本文件?
【发布时间】:2017-06-19 20:48:50
【问题描述】:

我创建了一个基本游戏作为学习练习的一部分,我想在学习更多 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()

My script is on GitHub 如果完整的脚本有用的话。我在这里进行了几次搜索,最接近我认为我需要的问题是this one。我不知道如何有效地实现这一点

我的主要挑战之一是弄清楚如何让脚本动态创建一个新的文本文件,然后用库存中的物品填充该文本文件

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    如果您需要在 python 中写入文件,请使用with open(...):

    ...
    
    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."
        with open("ex36_game_txt.txt", 'w') as inv:
            line3 = "10 gold coins"
            inv.write(line3)
    
        # 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()
    
    ...
    

    with open 将在您完成写入后自动处理异常并关闭文件。

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

    list_of_items = {item0: "...", item1: "...", ...}
    

    在单独的模块中定义它并在需要时导入它。然后您可以通过键访问它的值并在游戏期间将它们写入库存。

    我不确定您创建查看和库存选项究竟是什么意思。为什么不像你已经使用的那样使用raw_input() 并检查单词inventory

    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_input(),而是使用input()

    【讨论】:

    • 太棒了,谢谢。这很有帮助。我需要执行脚本并从命令行命名文本文件,还是脚本只创建一个名称为with open() 的文本文件?
    • @PaulJacobson 如果文件不存在,with open() 将在您使用参数w 时自动创建它。如果存在,文件将被重写。如果要追加到现有文件,则需要使用选项a
    【解决方案2】:

    如果您使用singleton design pattern.,则无需写入文本文件。它保证类始终返回一个自己的唯一实例。因此,您可以创建一个名为“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
    
    # 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")
    

    请注意,如果您将导入行放在开头,则每个文件只需要一次!

    【讨论】:

    • 我不太了解您所说的内容,但据我所知,这似乎是一种有趣的替代方法。谢谢。
    • 是的,我知道如果您将其作为一个学习练习并且不一定对面向对象编程了解很多,这可能会令人困惑!我将添加一个示例来说明这个概念。
    • 我查看了您的 github 存储库,作为一个友好的建议,我建议将您的代码拆分为多个源文件,这将有助于构建和维护它!祝你的游戏好运,开始学习 python 看起来是个不错且有趣的主意!
    • 感谢您的建议。一旦我弄清楚如何做到这一点并使其协同工作,我就会这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2014-10-10
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多