Reading all files in a directory without a loop

Viewed 56

I have been looking for days and was wondering if there is any way to read all the files in a directory in python without using a loop. The reason I ask is because when I go to write the files it goes through the loop again and overwrites all my information or doubles it when I only need to grab one file.

1 Answers

I love pathlib for such tasks

from pathlib import Path
# create a posix path object
folder_path = Path('/path/to/your/folder')
# iterate over directory and store filenames in a list
files_list = list(folder_path.iterdir())
# access file names
print(files_list[0].name)

always pretty handy

Related