例如,何时:
name = input('Please enter your name:\n')
并输入:William
关闭python shell后,变量“name”消失了。我如何保存这些信息,以便下次可以使用它?
答案 0 :(得分:1)
读取和写入文件:Python 3.5 documentation
filename = 'names.txt'
name = str(input('Give me your name, now!\nName: '))
with open(filename, 'w') as f: f.write(name)
with open(filename, 'r') as f: original_name = str(f.read()).strip()
在SQLite3数据库中存储信息:Python 3.5 Documentation
import sqlite3
name = str(input('Give me your name, now!\nName: '))
with sqlite3.connect('names.db') as conn:
cur = conn.cursor()
cur.execute(
'CREATE TABLE IF NOT EXIST Name (person_name TEXT);'
'INSERT INTO Name VALUES ({});'.format(name)
)
conn.commit()
original_name = cur.execute(
'SELECT * FROM Name'
).fetchall()[0]
将实际Python对象存储/序列化为文件(能够重新加载它们):Python 3.5 Documentation
import pickle
name = str(input('Give me your name, now!\nName: '))
with open('names.pkl', 'wb') as f:
pickle.dump(name, f)
with open('names.pkl', 'rb') as f:
original_name = pickle.load(f)