Python Forum
Put all files in a directory into list. How?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Put all files in a directory into list. How?
#3
this can be done with pathlib:

I use same path as script file, but you can substitute any path on line 23
note that I removed the '*' from EXTN pathlib wants just the suffix.
I put two files in my src directory, cows.mpeg and trigger.mp4
import pathlib
import os

# This does all the work:
def get_file_list(fpath):
    EXTN = ['.avi', '.flv', '.mkv', '.mov', '.mp4',
        '.mpeg', '.mpg', '.webm', '.wmv']

    if not isinstance(fpath, pathlib.PosixPath):
        fpath = (pathlib.Path(fpath))

    return [filename for filename in fpath.iterdir()
        if filename.is_file() and (filename.suffix in EXTN)]


def main():
    filelist = []

    # anchor starting directory to script path
    os.chdir(os.path.abspath(os.path.dirname(__file__)))

    #create a pathlib path, here it is current path
    fpath = pathlib.Path('.')

    filelist = get_file_list(fpath)

    for filename in filelist:
        print(f"{filename.name}")


if __name__ == '__main__':
    main()
results:
Output:
cows.mpeg trigger.mp4
Reply


Messages In This Thread
RE: Put all files in a directory into list. How? - by Larz60+ - Sep-18-2020, 10:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Filer and sort files by modification time in a directory tester_V 6 250 May-02-2024, 05:39 PM
Last Post: tester_V
  Loop through all files in a directory? Winfried 10 509 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  uploading files from a ubuntu local directory to Minio storage container dchilambo 0 497 Dec-22-2023, 07:17 AM
Last Post: dchilambo
  change directory of save of python files akbarza 3 940 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,487 Jun-27-2023, 01:17 PM
Last Post: diver999
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 1,688 May-07-2023, 12:33 PM
Last Post: deanhystad
  list the files using query in python arjunaram 0 691 Mar-28-2023, 02:39 PM
Last Post: arjunaram
  Read directory listing of files and parse out the highest number? cubangt 5 2,433 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  How to download a list of files from FTP? schnarkle 0 1,026 Jun-21-2022, 10:35 PM
Last Post: schnarkle
  How to save files in a separate directory Scordomaniac 3 1,999 Mar-16-2022, 10:17 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020