python - 运行程序时无法创建文本文件
问题描述
我想在当前目录中创建文本文件
我写了这段代码,它在 vscode 中工作:
import os
p = __file__
p = str(p)
f = open(p + '.txt', 'a')
f.write('hello world')
但是当我使用 pyinstaller 时它不会创建文本文件!!!
解决方案
看看下面的代码。使用 open() 函数时需要指定正确的文件权限。
import os
p = __file__
p = str(p)
try: # in the case that the file does not exist, you can use a try block to catch the error.
f = open(p + '.txt', 'w') # a works as well instead of w.
with f:
f.write('hello world')
except IOError:
print("Failed to open file.")
推荐阅读
- python - 为红绿灯添加发光效果 Imageprocessing skimage
- webrtc - 您能否提供一个 DispatcherOneToMany 的示例?
- java - 如何通过 JNDI 名称连接数据库?
- python - Return the index of selected test set Python
- asp.net-core-mvc - How to understand .netcore add scoped
- python - 数据采集和绘图在单独的线程中
- javascript - 如何将数组中的特定元素合并在一起?
- php - Laravel Nova 未按记录显示 userTimezone
- reactjs - 样式化组件需要什么严格类型?
- java - 关于 SQL Server jdbc 的字符串长度限制?