-6

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

Community
  • 1
  • 1
Gazzer
  • 1
  • 1
  • 1
  • 4

2 Answers2

2

I assume this is what you're asking for

text_file = open("Output.txt", "w")

text_file.write(stuff)

text_file.close()
SAMO
  • 458
  • 1
  • 3
  • 20
  • Yes that is what i was looking for thank you! – Gazzer Jun 27 '16 at 13:55
  • 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") text_file = open("Output.txt","w") text_file.save(sentence + input) text_file.close() It doesn't work in this code – Gazzer Jun 27 '16 at 14:04
  • 2
    1) The code you just commented doesn't include "text_file.write" try that... 2) You've posted a question that has already been answered: http://stackoverflow.com/questions/5214578/python-print-string-to-text-file and you are just asking for answers not for help – SAMO Jun 27 '16 at 14:06
1

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.

pat
  • 69
  • 2
  • 10