DeltaIV
DeltaIV

Reputation: 5646

Getting the absolute paths of all files in a folder, without traversing the subfolders

Let

my_dir = "/raid/user/my_dir"

be a folder on my filesystem, which is not the current folder (i.e., it's not the result of os.getcwd()). I want to retrieve the absolute paths of all files at the first level of hierarchy in my_dir (i.e., the absolute paths of all files which are in my_dir, but not in a subfolder of my_dir) as a list of strings absolute_paths. I need it, in order to later delete those files with os.remove().

This is nearly the same use case as

Get absolute paths of all files in a directory

but the difference is that I don't want to traverse the folder hierarchy: I only need the files at the first level of hierarchy (at depth 0? not sure about terminology here).

Upvotes: 0

Views: 1669

Answers (3)

Mark
Mark

Reputation: 92440

You can use os.scandir which returns an os.DirEntry object that has a variety of options including the ability to distinguish files from directories.

with os.scandir(somePath) as it:
    paths = [entry.path for entry in it if entry.is_file()]
print(paths)

If you want to list directories as well, you can, of course, remove the condition from the list comprehension if you want to see them in the list.

The documentation also has this note under listDir:

See also The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

Upvotes: 1

alexis
alexis

Reputation: 50190

It's easy to adapt that solution: Call os.walk() just once, and don't let it continue:

root, dirs, files = next(os.walk(my_dir, topdown=True))
files = [ os.path.join(root, f) for f in files ]
print(files)

Upvotes: 1

James
James

Reputation: 36608

You can use the os.path module and a list comprehension.

import os

absolute_paths= [os.path.abspath(f) for f in os.listdir(my_dir) if os.path.isfile(f)]

Upvotes: 1

Related Questions