Search code examples
pythonfiletexttext-filessaving-data

How do you save the inputs into text file?


How do i save the inputs of program into a file from the program. Python only: i need to add it to this:

TASK 2 AGAIN

sentence = input("Please input a sentence: ")
print(sentence)
word=input("Please enter word and position wil be shown: ")
if word in sentence:
    print("Found word")
else:
    print ("Word not found")

But i haven't got a clue


Solution

  • Your question seems to have two main parts to it: how do I get inputs in Python and how do I save data to a file in Python.

    To get input from the terminal:

    >>> data = input('Input: ')
    >>> Input: hello, world!
    

    To save to a file:

    >>> with open('output.txt', 'w') as f:
    >>>    f.write(data)
    

    You can find more information about inputs here and file i/o here

    Edit 0: @Gazzer, if you want to save sentence + input you'll need to do f.write(sentence + input) rather than using .save().

    Edit 1: @Gazzer, I got something like the below to work (note: the code does not show position of the found word):

    sentence = input("Please input a sentence: ")
    word = input("Please enter word and position wil be shown: ")
    with open('output.txt', 'w') as f:
        f.write('{} {}'.format(sentence, word))
    

    If you run into more issues, there are hundreds of resources all over the web to ask for help. Stack Overflow, learnprogramming, and many more.

    Next time you ask a question, it is really helpful for those answering if you provide a code snippet you are working on and what the problem/errors are.