Sommer
Sommer

Reputation: 11

How can I save ALL user input in a text file?

I did a questionnaire and I want to save all the user's input into a text file. Do you know what I can do?

def start():
    print("Hallo, ich bin Roni, Ihr Assistent rund um das Verhalten mit einem Coronaverdacht! ")
    print("Ich stelle Ihnen folgend einige wichtige Fragen.")
    print("Bitte achten Sie darauf Ja und Nein zu benutzen, außer Sie sind explizit dazu aufgefordert eine offene Frage zu beantworten!")
    print("Aus Datenschutzgründen teile ich Ihnen mit, dass die Konversation gespeichert wird.")
    print("Dies hilft uns dabei wichtige Daten schnell an die nötigen Instanzen zu schicken.")
    print("Na gut, dann fangen wir mal an :-)")

def verdacht():
    möglicher_verdacht = input("Haben Sie den Verdacht an COVID-19 erkrankt zu sein? (Ja/Nein): ")
    if möglicher_verdacht == "Ja":
        print("Ok, dann folgen nun ein paar Fragen! ")
    else:
        print("Bleiben Sie gesund und achten Sie auf die AHA+L Regel! ")
        
def kontakt():
    kontakt = input("Hatten Sie Kontakt mit einer an COVID-19 infizierten Person? (Ja/Nein): ")
    if kontakt == "Ja":
        symptome()
    else:
        symptome()

Upvotes: 0

Views: 802

Answers (3)

Raphael Ezeigwe
Raphael Ezeigwe

Reputation: 1

Get user input

user_input = input('user input: ')

Store in a list

user_list = []
user_list.append(user_input)

Open file with context managers so you don't have to close explicitly, then loop through the list and save your data.

with open('user_input.txt', 'a') as file:
    for item in user_list:
        file.write(item + '\n')

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23079

One way would be to capture your output at the level where you are running your Python script. At a Linux prompt, for example, you could use the tee tool to direct the output of your script to a file.

To write all output to a file inside your script, you need to change your code to actually send your input and output to two places. You could do that in a fancy way, by changing the definitions of the standard input and output streams such that they do this. That's a complicated thing to do and get just right.

Another option is to have your code use your own custom print and input functions that redirect all output to both the console and a file of your choosing.

I know you asked to only redirect user input to a file, but I've found that you often want to save both input and output so that you have some context to work with in terms of knowing why the user input what they did. So the most flexible solution would be to redirect both printed messages and user input through custom print and input routines, but then have a switch that lets you indicate if you want to save both messages and user input, or just user input.

Here's a demonstration of how to do that:

log_file_path = "/tmp/logfile.txt"
save_messages = False

def myprint(msg):
    if save_messages:
        with open(log_file_path, "a") as f:
            f.write(msg + '\n')
    print(msg)


def myinput(msg):
    with open(log_file_path, "a") as f:
        if save_messages:
            f.write(msg)
        result = input(msg)
        f.write(result + '\n')
    return result


def start():
    myprint("Hallo, ich bin Roni, Ihr Assistent rund um das Verhalten mit einem Coronaverdacht! ")
    myprint("Ich stelle Ihnen folgend einige wichtige Fragen.")
    myprint(
        "Bitte achten Sie darauf Ja und Nein zu benutzen, außer Sie sind explizit dazu aufgefordert eine offene Frage zu beantworten!")
    myprint("Aus Datenschutzgründen teile ich Ihnen mit, dass die Konversation gespeichert wird.")
    myprint("Dies hilft uns dabei wichtige Daten schnell an die nötigen Instanzen zu schicken.")
    myprint("Na gut, dann fangen wir mal an :-)")


def verdacht():
    möglicher_verdacht = myinput("Haben Sie den Verdacht an COVID-19 erkrankt zu sein? (Ja/Nein): ")
    if möglicher_verdacht == "Ja":
        myprint("Ok, dann folgen nun ein paar Fragen! ")
    else:
        myprint("Bleiben Sie gesund und achten Sie auf die AHA+L Regel! ")


def kontakt():
    kontakt = myinput("Hatten Sie Kontakt mit einer an COVID-19 infizierten Person? (Ja/Nein): ")
    if kontakt == "Ja":
        symptome()
    else:
        symptome()

This code will appear to run in just the same way as the original version, but after execution, the user's input will have been saved to the file '/tmp/logfile.txt'. If you set save_messages to True instead of False, then all of the text that went to the console, both messages and user input, will be found in the file /tmp/logfile.txt.

If you really only want to save the input, and so don't want to complicate your code to allow for saving the message output, you can use the same technique just to replace the input function. You'd then define your custom input function like this:

def myinput(msg):
    with open(log_file_path, "a") as f:
        result = input(msg)
        f.write(result + '\n')
    return result

Upvotes: 2

Matyas
Matyas

Reputation: 53

you could use a list to store all the inputs and create a file at the end.

Creating a list:

list = []

Adding to a list:

list.append(data to add)

Opening/Creating a file and writing to it:

file = open("filename.txt", "w")
file.write(list)

The file will be created in the same folder as the script

Close file when you are done:

file.close()

Upvotes: 0

Related Questions