top of page

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


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])
#False

Cause


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

Recent Posts

See All

[Python] Output pandas.DataFrame as json

Summary Data analysis is performed using python. The analysis itself is performed using pandas, and the final results are stored in pandas.DataFrame format. I want to output this result to a file in j

[Python] Conditionally fitting

Overview If you want to do fitting, you can do it with scipy.optimize.leastsq etc. in python. However, when doing fitting, there are many cases where you want to condition the fitting parameters. For

Comments


Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page