I have code like this:
for directory in os.listdir(path):
for file in os.listdir(path):
# Do stuff
I know there are only directories in path. Program creates .DS_STORE
in directory
and quits with Not a directory
error. The program was written for Linux and Windows and I don't want to change her. How could I prevent this behaviour?
CodePudding user response:
Add a check to see if the current directory is actually a directory.
for directory in os.listdir(path):
current_dir = os.path.join(path, directory) #creates the path to the current directory
if os.path.isdir(current_dir): #verify that the path is actually a directory
for file in os.listdir(current_dir):
current_file = os.path.join(current_dir, file) #create path to file inside directory
if os.path.isfile(current_file): #verify that the path is actually a file
# Do stuff
CodePudding user response:
I doubt that it's your program creating .DS_Store
files. They are usually created by Finder, and a program written for Linux and Windows is unlikely to create these macOS-specific files.
So the program can't handle unexpected file/dir hierarchy. I would argue that it's a problem with its design. You can clean up your dirs somehow before launching the program itself, but the natural way to fix the issue is to write more robust code handling common use cases.