Ioerror:[错误13]权限被拒绝:用Python写入文件(windows) [英] Ioerror: [errno 13] permission denied: while writing to a file in Python (windows)
问题描述
我正在尝试创建子文件夹并在最后一个子文件夹中创建一个文件并写入文件
例如: -
I想要在scripts26中创建一个文件夹scripts26和子文件夹folder,并创建一个文件test.txt并将This is a boy写入文件。
1)创建文件夹为: -
C:\ Users \admin \Desktop\scripts26 \ folder \ test.txt
注意:-test.txt也是作为文件夹内的子文件夹创建的
2)并且出现IO错误
我也尝试取消选中scripts26文件夹的只读权限。但是当我再次检查时它会重置。请帮忙。
这是我程序的输出: -
=============== RESTART:C:/ Users / admin /桌面/ scripts / de.py ===============
创建路径
Traceback (最近一次调用最后一次):
文件C:/ Users / admin / Desktop / scri pts / de.py,第6行,在< module>
中打开(mypath,w)为x:
IOError:[Errno 13]权限否认:'C:/Users/admin/Desktop/scripts26/folder/test.txt'
>>>
我尝试过:
我的代码: -
======= >
import os
mypath =C:/Users/admin/Desktop/scripts26/folder/test.txt
如果不是os.path.exists(mypath):
os.makedirs(mypath,0755);
print创建路径
打开(mypath,w)为x:
x.write(这是一个男孩)
你使用文件名作为目录的名称,然后尝试写入它,就好像它是一个文件。您需要创建没有附加文件名的文件夹,因此:
import os
mypath = C:/ Users / admin / Desktop / scripts26 / folder
if not os.path.exists(mypath):
os.makedirs(mypath, 0755 )
print 创建路径
fname = mypath + / + test.txt
打开(fname, w) as x:
x.write( 这是一个男孩 )
I am trying to create subfolders and create a file inside last subfolder and write to the file
For eg:-
I want to create a folder "scripts26" and subfolder "folder" inside "scripts26" and create a file"test.txt" and write "This is a boy" to file.
1) It is creating folders as:-
C:\Users\admin\Desktop\scripts26\folder\test.txt
Note:-test.txt is also created as a subfolder inside folder
2)And failing with IO error
I have also tried unchecking the readonly permissions for scripts26 folder.But it resets when I check it again.Please help.
Here is the output of my program:-
=============== RESTART: C:/Users/admin/Desktop/scripts/de.py ===============
Path is created
Traceback (most recent call last):
File "C:/Users/admin/Desktop/scripts/de.py", line 6, in <module>
with open(mypath,"w") as x:
IOError: [Errno 13] Permission denied: 'C:/Users/admin/Desktop/scripts26/folder/test.txt'
>>>
What I have tried:
My Code:-
=======
import os
mypath ="C:/Users/admin/Desktop/scripts26/folder/test.txt"
if not os.path.exists(mypath):
os.makedirs(mypath,0755);
print"Path is created"
with open(mypath,"w") as x:
x.write("This is a boy")
You are using the file name as the name of the directory and then trying to write to it as if it was a file. You need to create the folder without the appended file name, thus:
import os mypath ="C:/Users/admin/Desktop/scripts26/folder" if not os.path.exists(mypath): os.makedirs(mypath,0755) print"Path is created" fname = mypath + "/" + "test.txt" with open(fname,"w") as x: x.write("This is a boy")
这篇关于Ioerror:[错误13]权限被拒绝:用Python写入文件(windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!