我试图将用户输入数据存储在另一个python文件的字典中。这是我的第一个真正的python项目,所以如果你有任何关于简化我正在做的事情的建议,请建议。谢谢!
My Assignment类:
class Assignment(object):
def __init__(self, assignment_name, due_date):
self.assignment_name = assignment_name
self.due_date = due_date
def getassignment_name(self):
return self.assignment_name
def getdue_date(self):
return self.due_date
def __str__( xself):
return "%s is due on %s" % (self.assignment_name, self.due_date)
用户输入:
def questions():
raw_input("Name Of Assignment?")
raw_input("Due Date")
assignment_name = raw_input("Name Of Assignment?")
due_date = raw_input("Due Date")
assignment_data = Assignment(assignment_name,due_date)
试图将数据移动到另一个.py文件中的字典中。
f = open(assignments.py)
f.write(str(assignment_data))
f.close()
print assignment_data
print "ok"
f = open(assignments.py)
assignment_data = eval(f.read())
f.close()
pickle也可以用于在程序之间,甚至在同一程序的不同运行之间存储数据:从模块1:
import pickle
f = open(file_Name,'wb')
pickle.dump(assignment_data, f)
f.close()
from module 2:
import pickle
f = open(file_Name,'rb')
pickle.load(assignment_data, f)
f.close()
(更优雅地使用'with ......')
泡菜。Load知道它正在获取一个字典,并且它需要在两个方向上都使用二进制模式。
# create dictionary
assignment_data = {"name": "jane", "date": "late"}
# save dictionary
with open("assignments.py", "wt") as f:
f.write(repr(assignment_data))
# load dictionary
with open("assignments.py", "rt") as f:
assignment_data = eval(f.read())
print assignment_data