为什么变量在写入文本文件时会换行?

2024-04-26 14:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,我读取的信息作为变量,作为我的游戏保存系统。问题是我需要我的文档读写到某一行,它在第一次读写时工作正常,但是第二次行在它上移一行之前,我得到“索引超出范围”,因为我试图写/读的行是空的。你知道吗

First Read Write

enter image description here

我看了我的代码,似乎找不到问题。。你知道吗

gold=(60)
goldtxt=(str(gold) + 'gp')
inventory=['empty','empty','empty','empty','empty','empty','empty','empty','empty','empty',]

def ItemAdd(event):
   gamestatus = linecache.getline('C:Location', 2).rstrip() 
   if gamestatus == 'gamestatus1':       
      gameinfo1[7] = (inventory[(-1)]).strip('empty') + ' '
      gameinfo1[9] = goldtxt + '             '
      with open('C:Location', 'w') as active:
         active.writelines(gameinfo1) 
         RefreshTexts() 

def RefreshTexts():
    with open('C:Location', 'r') as file: 
        datatemplate = file.readlines() 
    with open('C:Location', 'r') as file: 
        gameinfo1 = file.readlines() 
    with open('C:Location', 'r') as file: 
        gameinfo2 = file.readlines() 
    with open('C:Location', 'r') as file: 
        gameinfo3 = file.readlines() 
    with open('C:Location', 'r') as file: 
        activeinfo = file.readlines()

我有一千多行,但我认为这就是问题所在,如果有一行的话。你知道吗


Tags: defaswithlocationopenfileemptyactive
1条回答
网友
1楼 · 发布于 2024-04-26 14:28:26

我认为出现错误的原因可能是因为您使用的是rstrip在某些地方去掉了行末尾的换行符;也可能是因为您使用的是linecache;尽管Python 2文档中提到了一般的行随机访问,但在Python 3中,文档清楚地指出:

The linecache module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback.

在任何情况下,使用linecache都不适合您的用例,因为linecache假定文件没有更改,但是您的保存文件确实更改了;并且您在保存之后正在刷新它们。我建议您使用^{}^{}将游戏状态数据保存并加载到单个字典中

比如:

import json

def save_game(game_data):
    with open('mysavedgame', 'w') as save_file:
        json.dump(game_data, save_file)

def load_game():
    with open('mysavedgame', 'r') as save_file:
        return json.load(save_file)

def new_game():
    return {
        'items': [],
        'money': 0
    }

# when starting a new game
game_data = new_game()

# adding items, money:
game_data['items'].append('Crystal sword')
game_data['money'] += 60

# when saving a game, use
save_game(game_data)

# and load the data with
game_data = load_game()
print(game_data)

运行程序打印

{'money': 60, 'items': ['Crystal sword']}

mysavegame的内容是

{"money": 60, "items": ["Crystal sword"]}

相关问题 更多 >