python - 在文件中的某个点追加,每次增加一个值

标签 python python-2.7

我对编程完全陌生。这是我的第一个将被其他人使用的“合适的”项目。

程序会询问各种问题,然后将新的商店条目写入文件。对于一个空文件,我的大部分工作正常,但成品需要在现有文件中的特定点插入条目。

有两个问题让我感到困惑:

如何在“Back:”之前将新的商店条目插入到文件中,以及如何在每次添加条目时将“InventoryLocation:”递增 1

被附加到的文件具有以下结构:

# shop 1
SuperSpaceSquids:
   RewardType: playercommand
   PriceType: free
   Reward:
   - ewarp Shop-SuperSpaceSquids
   MenuItem:
   - type:SKULL_ITEM
   - playerhead:MHF_Squid
   - durability:3
   - amount:1
   - name:&5SuperSpaceSquids
   - 'lore:&6&o"Squid Shop From Space!"'
   Message: ''
   InventoryLocation: 38
   ExtraPermission: ''
# shop 2
HadesKitty:
   RewardType: playercommand
   PriceType: free
   Reward:
   - ewarp Shop-HadesKitty
   MenuItem:
   - type:SKULL_ITEM
   - playerhead:Turtle_Em
   - durability:3
   - amount:1
   - name:&5HadesKitty
   - 'lore:&6&o"our prices are fair!..."'
   Message: ''
   InventoryLocation: 39 # This value needs to be incremented by 1 each time
   ExtraPermission: ''
>> insert new shops here <<
Back:
   RewardType: shop
   PriceType: free
   Reward: Shop_Menu
   MenuItem:
   - type:REDSTONE
   - amount:1
   - name:&cBack
   - lore:&8Back to Shop Menu
   InventoryLocation: 54

这是写入文件的函数:

def write(shop, id, data, desc, skull):
    f = open('file.yml', 'w')
    f.write("  %s:" % shop)
    f.write("\n    RewardType: playercommand")
    f.write("\n    PriceType: free")
    f.write("\n    Reward:")
    f.write("\n    - ewarp shop-%s" % shop)
    f.write("\n    MenuItem:")
    if skull:
        f.write("\n    - Type:SKULL_ITEM")
        f.write("\n    - playerhead:%s" % skull)
        f.write("\n    - durability:3")
    if not skull:
        f.write("\n    - id:%s" % id)
    if data:
        f.write("\n    - durability:%s" % data)
    f.write("\n    - amount:1")
    f.write("\n    - name:&5%s" % shop)
    f.write("\n    - 'lore:&6&o\"%s\"'" % desc)
    f.write("\n    Message:")
    f.write("\n    InventoryLocation:")
    f.write("\n    ExtraPermission: ''")
    f.flush()
    print "\nAll done."
    print "\nHit Return to quit or 1 to add more shops."

    while True:
        choice = raw_input(prompt)
        if choice == "":
            print "\nGoodbye!"
            f.close()
            time.sleep(2)
            exit(0)
        elif choice == "1":
            os.system('cls' if os.name == 'nt' else 'clear')
            input()
        else:
            print "I dont understand that."

最佳答案

这是一个很好的问题。我为你写了两个函数:

insert_before_back(列表,列表)

insert_before_back 获取文件行的​​列表和要在 Back: 之前添加的所有行的列表,然后返回一个列表,其中添加到正确索引中的项目。

add_inventory(列表,字符串)

add_inventory 接受文件行的列表和您希望增加其库存的商店名称。然后它遍历并将该数字递增 1,并将列表中的值重置为新递增的值。它返回新行的列表。

您可以使用这些来修改您读入的行的列表,然后只需遍历列表中所有新修改的项目并将每个项目写入具有相同名称的文件。

这是我使用这两个函数的示例:

def insert_before_back(lines, thingsToAdd):
    backIndex = lines.index('Back:\n')
    for item in reversed(thingsToAdd):
        lines.insert(backIndex, item)
    return lines

def add_inventory(lines, shopName):
    shopFound = 0
    for i in range(len(lines)):
        if shopName in lines[i]:
            shopFound = 1
        if 'InventoryLocation:' in lines[i] and shopFound:
            shopFound = 0
            lineSplit = lines[i].split(': ')
            incrementInventory = str(int(lineSplit[-1]) + 1)
            lineSplit[-1] = incrementInventory + '\n'
            lines[i] = ': '.join(lineSplit)


newLines = []
with open('input.txt', 'r') as f:
    inputLines = f.readlines()
    newLines = insert_before_back(inputLines, ['Hello\n', 'From\n', 'heinst\n'])
    add_inventory(newLines, 'HadesKitty')

with open('output.txt', 'w') as f:
    for line in newLines:
        f.write(line)

关于python - 在文件中的某个点追加,每次增加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329910/

相关文章:

python - 来自 Python : No module named lambda_function 的 AWS 错误

python - 找出Python对象的创建位置

python - 如何使用可变长度序列的序列拆包?

python - 集合中的numpy数组坐标

python - 在 Python 中写入和读取相同的 csv 文件

python - Pandas Apply 函数返回两个新列

python-2.7 - 类 HttpTransport 没有属性 '_HttpTransport__get_request_url' python 错误

python - PyQt 自动完成 QlineEdit 不显示列表项

python - 如何在每次运行 python 程序时添加新列

python - TensorFlow python : Accessing individual elements in a tensor