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
  • 39
  • 5
  • 2
    you should take a look at this https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file – penguin Jun 03 '20 at 22:33
  • Does @penguin's suggestion answer your question? [Correct way to write line to file?](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) – TheTechRobo the Nerd Jun 03 '20 at 22:42
  • 2
    If I run your program I get an error which tells me why it's failing to write to the file. – redbirdo Jun 03 '20 at 22:44

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
  • 2,047
  • 1
  • 4
  • 20
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
  • 2,047
  • 1
  • 4
  • 20
desert_ranger
  • 1,096
  • 3
  • 13
  • 26