-2
def example():
    print("hello, world!")

times = int(input("how many 'hello worlds'? "))
for c in range(times):
    example()

That's an example of what I'm trying to do.

If I type "3" in the input, I want my .txt file to contain the output of the function I created, which is:

hello, world!
hello, world!
hello, world!

Is that possible? If so, how?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    is your question how to do it with python specifically? or how to redirect the output to a file in general? – Mateo Torres Sep 02 '21 at 16:51
  • 2
    There's a chapter "[Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)" in the tutorial ... if that is your question. – Matthias Sep 02 '21 at 16:53
  • You can use [`contextlib.redirect_stdout`](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout). – martineau Sep 02 '21 at 17:07

3 Answers3

0

Of course you can! First you need to open the file, for which it is important that the program you are writing is in its folder. Here's how to do it: open ('the_file_name.txt', 'a') ("a" as append). Of course, you haven't written in yet. You can do this by adding the file argentum to the print command: print ('hello, world!', File = 'the_file_name.txt') Full code:

open ('the_file_name.txt', 'a')
def example ():
         print ("hello, world!", file = 'the_file_name.txt')

times = int (input ("how many 'hello worlds'?"))
for c in range (times):
     example ()  
Matyedli
  • 11
  • 3
-1
def example():
    print("hello, world!")

times = int(input("how many 'hello worlds'? "))

If you want to write a new file on each loop, open the file as 'w', so

output = ''
for c in range(times):
    output = f'{output}{example()}\n'
with open('./MyFile.txt', 'w') as f:
    f.write(output)

Also, if you want to write without clear the file, open as 'a' that is append, so

with open('./MyFile.txt', 'a') as f:

But make sure that the file already exists

Joel Borrero
  • 97
  • 1
  • 5
  • 1
    You didn't try this, or did you? If yes, I wonder what a strange version of Python you're running. (Even after your second edit this still is wrong. Please try it before posting an answer.) – Matthias Sep 02 '21 at 16:54
-1

you can re-write the code a bit, but it should save the 'hello, world' text on a new line for now.

def example():
return "hello, world!"


times = int(input("how many 'hello worlds'? "))
data = []
for c in range(times):
    data.append(example())

file = open('finename.txt', 'w')
with file as f:
  for line in data:
    f.write(f'{line}\n')
MarcusDev
  • 34
  • 2