假设我编写了一些代码,其他人使用并输入他们的名字,并执行代码具有的其他内容。
name = input('What is your name? ')
money = 5
#There is more stuff, but this is just an example.
我如何能够将该信息保存到一个文本文件中,以便稍后调用以继续该会话。就像电子游戏中的保存点。
假设我编写了一些代码,其他人使用并输入他们的名字,并执行代码具有的其他内容。
name = input('What is your name? ')
money = 5
#There is more stuff, but this is just an example.
我如何能够将该信息保存到一个文本文件中,以便稍后调用以继续该会话。就像电子游戏中的保存点。
您可以将信息写入文本文件。例如:
(empty)
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.
与@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 模块来读取和写入会话信息,因此在写入文件后对其进行篡改可能会导致无法预料的结果;所以要小心,它只是写入和读取该文件的程序
您可能正在寻找一种通用机制,以某种方式更轻松地保存和恢复所需信息。这被称为持久性作为编程中的术语。但是,它不是自动的。有一些技术如何实现它。实施的系统越复杂和具体,机制就越具体。
对于简单的情况,将数据显式存储到文件中就可以了。正如 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)