[python]Os.path.isdir () is False even though it exists
- M.R

- Aug 19, 2021
- 1 min read
Situation
I want to get a list of files and folders directly under the directory by os.listdir () and operate on the folders in it. However, when the element of the array obtained by listdir is taken as the argument of the os.path.isdir () method, it becomes False for some reason (of course, the folder exists).
Further investigation reveals that when os.listdir () is done with the target directory as the current directory, it becomes True. It seems that if the target directory is taken as an argument of the listdir method as a variable with the os.path.join () method, it will be False.
import os
base_dir=r"C:\Users\Desktop"
os.chdir(base_dir)
path=os.path.join(base_dir, "test")
listdir=os.listdir(path)
# listdir: ['a', 'b', 'c']os.path.isdir(listdir[0])
#FalseCause
A closer look at the listdir element contained a' (I'm not sure why).
repr(listdir[0])
# "'a'"If you join again with os.path.join, it will work.
fol=os.path.join(path, listdir[0])
os.path.isdir(fol)
# True





Comments