Click here to Skip to main content
15,120,739 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:-


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/ ===============
Path is created

Traceback (most recent call last):
File "C:/Users/admin/Desktop/scripts/", 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):
print"Path is created"
with open(mypath,"w") as x:
x.write("This is a boy")
Updated 16-Oct-18 4:07am

1 solution

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):
    print"Path is created"
fname = mypath + "/" + "test.txt"
with open(fname,"w") as x:
    x.write("This is a boy")

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900