python - 如何在 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()
解决方案
推荐的打开和写入文件的方法如下:
with open(file_path, 'w') as file:
file.write(f'Pi is {pisquare}')
我们使用上下文管理器with
,因此文件在完成后会自动关闭.write()
。我相信,当您的程序过早退出时,这可以防止内存损坏。
但是,您可能已经注意到,您的问题来自这一行:
f.write("Pi is ", pisquare)
你给出了.write()
两个参数而不是一个字符串。
推荐阅读
- winforms - 在 Windows 10 上的 Visual Studio 2017 调试期间无法通过 Alt + Tab 找到 Windows 窗体
- python - 使用 Python 命令运行:python,ImportError: No module named pyproj
- javascript - Google 语音转文本 API 示例代码将无法运行
- rust - Rust 相当于 Swift 对协议的扩展方法?
- docker - Docker 与 ubuntu 用户共享文件权限
- http - 如何在 Angular 6 中使用 etag 实现缓存?
- uwp - UWP 更改 StorageFile 的缩略图
- angular - 为什么 Angular 代理服务器将原始 url 复制到请求 url?
- user-interface - 如何在 Flutter 中进行高级 UI 设计
- python - 带有 Kivy 和 Buildozer 的 Android 应用程序无法正确读取 WhatsApp 聊天