0

Could someone please explain why this code won't write to a text file? I run the code but a text file is not created and also cannot be opened using f.open("data.txt","r")

f = open("data.txt", "w+")
n = 1
s = 0
for n in range(1, 999999):
    s  += 1/n**2
    print(s, end="\r")
x = s*6
pisquare = math.sqrt(x)
f.write("Pi is ", pisquare)
f.close()
TGFoxy
  • 45
  • 5

2 Answers2

2

The recommended way to open and write to a file is as follow:

with open(file_path, 'w') as file:
    file.write(f'Pi is {pisquare}')

We use the context manager with so the file closes automatically when done with .write(). This prevents memory corruption when your program exits prematurely I believe.

However, as you have probably noticed, your problem comes from this line:

f.write("Pi is ", pisquare)

You are giving .write() two arguments rather than one string.

Sy Ker
  • 1,810
  • 1
  • 3
  • 17
1
import math
f = open("data.txt", "w+")
n = 1
s = 0
for n in range(1, 999999):
    s  += 1/n**2
    print(s, end="\r")
x = s*6
pisquare = math.sqrt(x)
f.write("Pi is " + str(pisquare))
f.close()

I am able to create the text file. Please check for it in your current directory. But if I understand your code correctly, this is what you are looking for -

import math

n = 1
s = 0
with open("data.txt", "w+") as f:
    for n in range(1, 9999):
        s  += 1/n**2
        print(s, end="\r")
        x = s*6
        pisquare = math.sqrt(x)
        f.write(" Pi is " + str(pisquare) + "\n")
Sy Ker
  • 1,810
  • 1
  • 3
  • 17
desert_ranger
  • 614
  • 1
  • 8
  • 19