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 fileFor 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.txtNote:-test.txt is also created as a subfolder inside folder2)And failing with IO errorI 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 createdTraceback (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 osmypath ="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 osmypath ="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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-31 04:47