-1

I would like to export the output of this python (see below). This code will be timed. I am not sure how to export it into a text file for other uses. I have tried the other question, but it doesn't work with my code. Which part of my code is needed to be exported?

import time
start_time = time.time()

def calcPi(limit):
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    decimal = limit
    counter = 0
    while counter != decimal + 1:
            if 4 * q + r - t < n * t:
                    yield n
                    if counter == 0:
                            yield '.'
                    if decimal == counter:
                            print('')
                            break
                    counter += 1
                    nr = 10 * (r - n * t)
                    n = ((10 * (3 * q + r)) // t) - 10 * n
                    q *= 10
                    r = nr
            else:
                    nr = (2 * q + r) * l
                    nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
                    q *= k
                    t *= l
                    l += 2
                    k += 1
                    n = nn
                    r = nr
def main():
    pi_digits = calcPi(int(input(
        "Enter the number of decimals to calculate to: ")))
    i = 0
    for d in pi_digits:
            print(d, end='')
            i += 1
            if i == 200:
                print("")
                i = 0

if __name__ == '__main__':
    main()

print("--- %s seconds ---" % (time.time() - start_time))
Will
  • 31
  • 4
  • 8
    Just redirect the stdout to a file – DarkKnight Dec 19 '22 at 08:58
  • You can also open a file in write mode and append to it... – SergeD Dec 19 '22 at 09:00
  • 1
    One good option would be to learn about "Shell Redirection" (the ">" operator in Bash), i.e. changing the way you call the program. – mnagel Dec 19 '22 at 09:06
  • 1
    Another good option would be to make a little change to the behavior of the program and have it write to a file. You can explicitly open a file and write there or your could redirect stdout (your print commands) there. – mnagel Dec 19 '22 at 09:07

2 Answers2

0

Here's a quick solution, without too many details. You can open a txt file and then redirect the output to it:

sourceFile = open('demo.txt', 'w')
print('Hello, Python!', file = sourceFile)
sourceFile.close()

More info: https://howtodoinjava.com/python-examples/python-print-to-file/

waykiki
  • 914
  • 2
  • 9
  • 19
0

The common way for writing to files in python is:

with open("myfile.txt", "w") as fp:
    fp.write(data)

…where myfile.txt is your output file, w is the file pointer mode = "write" in this case, fp is the file pointer you just opened and the method .write is used to write your text data to that file.

gustafbstrom
  • 1,622
  • 4
  • 25
  • 44