简体   繁体   中英

How to save user input and store for later use in Python3

So I've been trying to make a python program which can save all my ideas for future projects(I was bored). Everything has been going well, its just that I ran into a small problem. To save my ideas, I use input() and then appending the input into a list. I realized that whenever you put something inside the list, whenever you re-run the program, the string you put into the list doesn't save. So I tried pickling but the data inside of it keeps getting overwritten. Could someone help me with this? I don't know where to start. Thanks for the help!

(Please keep in mind that I'm a beginner)

As a fun project for you, you can learn how to connect to a database and insert it as a row there. It is a simple procedure. You can try with SQLite, its easy and will be great learning for you.

If I get it right, you want to save your data when it is closed and after opening again, you want to access it.
you can use databases and for small projects, it is enough to use sqlite :

import sqlite3
conn = sqlite3.connect('test.db')
conn.execute('''CREATE TABLE COMPANY
         (ID INT PRIMARY KEY     NOT NULL,
         NAME           TEXT    NOT NULL,
         AGE            INT     NOT NULL,
         ADDRESS        CHAR(50),
         SALARY         REAL);''')

conn.close()

you can begin here and see some examples.

Even file handling will be helpful, try this: (The term "yield" refers here in python as generator - you can learn: https://www.w3schools.com/python/ )

def store_ideas():
    print('Please place your ideas below, press enter to exit')
    while True:
        idea = input()
        if "quit" in idea or "exit" in idea:
            break
        else:
            yield idea

ideas = [x for x in store_ideas()]

with open('myideas.txt', 'a') as fp:
    for idea in ideas:
        fp.write(str(f'{idea}\n'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM