如何保存会话数据(Python)

时间:2013-08-19 06:53:23

标签: python

假设我编写了一些代码,并且有其他人使用,并输入他们的名字,并执行代码所具有的其他内容。

name = input('What is your name? ')
money = 5
#There is more stuff, but this is just an example.

我怎样才能将这些信息保存到稍后要调用的文本文件中以便在该会话中继续。就像电子游戏中的保存点一样。

3 个答案:

答案 0 :(得分:0)

您可以将信息写入文本文件。例如:

mytext.txt

(empty)

myfile.py

name = input('What is your name? ')
... 
with open('mytext.txt', 'w') as mytextfile:
    mytextfile.write(name)
    # Now mytext.txt will contain the name.

然后再次访问它:

with open('mytext.txt') as mytextfile:
    the_original_name = mytextfile.read()

print the_original_name
# Whatever name was inputted will be printed.

答案 1 :(得分:0)

使用@ Justin的评论,以下是我每次保存和阅读会话的方式:

import cPickle as pickle

def WriteProgress(filepath, progress):
    with open(filepath, 'w') as logger:
        pickle.dump(progress, logger)
        logger.close()

def GetProgress(filepath):
    with open(filepath, 'r') as logger:
        progress = pickle.load(logger)
        logger.close()
    return progress

WriteProgress('SaveSessionFile', {'name':'Nigel', 'age': 20, 'school': 'school name'})
print GetProgress('SaveSessionFile')

{'age': 20, 'name': 'Nigel', 'school': 'school name'}

这样,当您再次阅读该文件时,您可以拥有之前声明的所有可变数据,并从您离开的地方开始。

请记住,由于您的程序使用pickle模块来读取和写入会话信息,因此在写入文件后篡改文件会导致无法预料的结果;所以要小心,只有程序写入和读取该文件

答案 2 :(得分:0)

您可能正在搜索一种通用机制,可以更轻松地以某种方式保存和恢复所需信息。这称为 persistence 作为编程中的术语。但是,它不是自动的。有技术如何实现它。实施的系统越复杂和具体,机制就越具体。

对于简单的情况,将数据显式存储到文件中就可以了。正如Smac89在https://stackoverflow.com/a/18309156/1346705中所示,pickle模块是如何保存整个Python对象状态的标准方法。但是,你不一定需要它。

更新:以下代码显示了原理。它应该针对实际使用进行增强(即不应该以这种方式使用,仅在教程中使用)。

#!python3

fname = 'myfile.txt'

def saveInfo(fname, name, money):
    with open(fname, 'w', encoding='utf-8') as f:
        f.write('{}\n'.format(name))
        f.write('{}\n'.format(money))  # automatically converted to string

def loadInfo(fname):
    # WARNING: The code expect a fixed structure of the file.
    #   
    # This is just for tutorial. It should never be done this way
    # in production code.'''
    with open(fname, 'r', encoding='utf-8') as f:
        name = f.readline().rstrip()   # rstrip() is an easy way to remove \n
        money = int(f.readline())      # must be explicitly converted to int
    return name, money              


name = input('What is your name? ')
money = 5
print(name, money)

# Save it for future.
saveInfo(fname, name, money)

# Let's change it explicitly to see another content.
name = 'Nemo'
money = 100
print(name, money)

# Restore the original values.
name, money = loadInfo(fname)
print(name, money)