Python:在写入文件到Windows目录时出现PermissionError

1 投票
2 回答
6528 浏览
提问于 2025-05-01 00:41

当我想在C:\(Windows目录)打开一个文件时,出现了这个错误:
PermissionError: [Errno 13] 权限被拒绝: 'C:\h.txt'

我该怎么办呢?

我知道这个问题已经被问过很多次,但我找不到解决办法!

代码:

f=open ('C:\\h.txt','w')
f.write ('python')
f.close
暂无标签

2 个回答

0

我不是在Windows电脑上,不过你可以试着在c:\Temp这个文件夹里创建这个文件。

另外,确保你没有在打开记事本等程序查看这个文件。

1

我不是在Windows机器上,但你可以试试这个方法,你可以通过这些命令来管理权限。试着用os.fdopen来打开你的文件。

 import os
 with os.fdopen(os.open('file.txt', os.O_WRONLY | os.O_CREAT, 0600), 'w') as f:
   f.write(...)     

更新

import os
is_accessible = os.access("C:\\temp\\python",os.F_OK) #Check if you have access, this should be a path
if is_accessible == False: #If you don't, create the path
     os.makedirs("C:\\temp\\python")
os.chdir("C:\\temp\\python") # Check now if the path exist 
f = os.open( "p.txt", os.O_RDWR|os.O_CREAT ) #Create the file 
os.write(f, b"This is a test \n")  #Try to write 
os.close(f)

撰写回答