Python open() 创建文件时引发错误

-2 投票
2 回答
896 浏览
提问于 2025-04-17 04:22

我在Windows上用Python 2.6时遇到了一个问题。
无论我尝试:

fileobj=open("nonexistent.txt","w")

还是

fil=os.open("nonexistent.txt", os.O_CREAT)
fileobj=file(fil)

我都会收到一个错误提示:

IOError: [Errno 2] 没有这样的文件或目录: 'nonexistent.txt'

这可能是什么问题呢?

2 个回答

-1

这看起来像是权限问题。试着在其他地方打开这个文件,或者以管理员身份运行Python。

-1

如果文件不存在,你是无法读取它的,不过你应该还是可以写入的。下面的代码会返回同样的错误吗?

f=open("nonexistent.txt","w")
f.write('Test')
f.close()

撰写回答