首页 > 解决方案 > 如何在 python 3 中写入文本文件?

问题描述

有人可以解释为什么这段代码不会写入文本文件吗?我运行代码,但未创建文本文件,也无法使用 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()

标签: python

解决方案


推荐的打开和写入文件的方法如下:

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

我们使用上下文管理器with,因此文件在完成后会自动关闭.write()。我相信,当您的程序过早退出时,这可以防止内存损坏。

但是,您可能已经注意到,您的问题来自这一行:

f.write("Pi is ", pisquare)

你给出了.write()两个参数而不是一个字符串。


推荐阅读