salius
salius

Reputation: 113

os.path.isfile() return False

why this code return nothing?

>>> [f for f in os.listdir('Scripts') if os.path.isfile(os.path.abspath(f))]
[]
>>> os.listdir('Scripts')
['dmypy.exe', 'easy_install-3.8.exe', 'easy_install.exe', 'f2py.exe', 'futurize.exe', 'iptest.exe', 'iptest3.exe', 'ipython.exe', 'ipython3.exe', 'mypy.exe', 'mypyc', 'pasteurize.exe', 'pip.exe', 'pip3.8.exe', 'pip3.exe', 'prichunkpng', 'priforgepng', 'prigreypng', 'pripalpng', 'pripamtopng', 'pripnglsch', 'pripngtopam', 'priweavepng', 'pygmentize.exe', 'pyi-archive_viewer.exe', 'pyi-bindepend.exe', 'pyi-grab_version.exe', 'pyi-makespec.exe', 'pyi-set_version.exe', 'pyinstaller.exe', 'stubgen.exe', 'stubtest.exe', 'wheel.exe']

I understand the answer from this question Why do os.path.isfile return False?, but here I've added a full path to the filename, but anyway it is don't working

Upvotes: 0

Views: 1920

Answers (2)

quamrana
quamrana

Reputation: 39354

Your code returns an empty list because os.path.abspath() simply appends the given filename onto the current directory and none of those files are actually present in the current directory.

If you want to get all the files from the Scripts folder then you need to go with the answer from @Roy2012

Upvotes: 0

Roy2012
Roy2012

Reputation: 12503

abspath isn't the right tool here. Use os.join with the "Scripts" directory instead:

[f for f in os.listdir('Scripts') if os.path.isfile(os.path.join("Scripts", f))]

With regards to abspath - according to the documentation, it basically joins the current working directory to the filename. This is not what you want if the files you're looking into aren't in the current directory.

Quoting the documentation:

abspath: ... On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

Upvotes: 3

Related Questions