首页 > 解决方案 > 运行程序时无法创建文本文件

问题描述

我想在当前目录中创建文本文件

我写了这段代码,它在 vscode 中工作:

import os
p = __file__
p = str(p)
f = open(p + '.txt', 'a')
f.write('hello world')

但是当我使用 pyinstaller 时它不会创建文本文件!!!

标签: pythonpyinstaller

解决方案


看看下面的代码。使用 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.") 

推荐阅读