Reputation: 73
I have a directory with a set of files in it. I'm trying to create a folder for each filename inside the existing directory, and name it the given filename. but i'm getting an I/O error permission denied... what is wrong with this code?
import os
path = "C:/Users/CDGarcia/Desktop"
os.chdir(path)
gribs = os.listdir("testgrib")
print gribs
print os.getcwd()
if not os.path.exists(os.path.basename("gribs")):
os.makedirs(os.path.dirname("gribs"))
with open(path, "w") as f:
f.write("filename")
Upvotes: 2
Views: 2683
Reputation: 387557
os.path.dirname()
does not do what you expect it to do. It returns the directory name for the path you pass to it. So it interprets whatever string you pass as a path. As such, when you pass a path that has no directory part, it returns an empty string:
>>> os.path.dirname("gribs")
''
So with os.makedirs()
you are trying to create an empty directory, which of course will not create the path you are looking for.
Instead, you should just use os.makedirs('gribs')
to create gribs
folder relative to your current directory.
Furthermore, open(path)
will not work when path
is the path to the desktop directory. You will have to pass a path to a file there. You probably meant to use a file path relative to the folder you create there:
with open('gribs/something.txt', 'w+') as f:
f.write('example content')
Upvotes: 1