J.William
J.William

Reputation: 11

How do I store the user information in python so that i can keep using it next time?

For example, when :

name = input('Please enter your name:\n')

and input : William

after I close the python shell the variable "name" is gone. How can i save this information so that i can use it for next time?

Upvotes: 0

Views: 1408

Answers (1)

Sean Pianka
Sean Pianka

Reputation: 2325

Reading and writing to files: 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()

Storing information in a SQLite3 database: 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]

Storing/serializing actual Python objects into files (with the ability to reload them): 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)

Upvotes: 1

Related Questions