Find all CSV files in a directory using Python

后端 未结 11 1785
生来不讨喜
生来不讨喜 2020-12-02 17:57

How can I find all files in directory with the extension .csv in python?

11条回答
  •  甜味超标
    2020-12-02 18:31

    While solution given by thclpr works it scans only immediate files in the directory and not files in the sub directories if any. Although this is not the requirement but just in case someone wishes to scan sub directories too below is the code that uses os.walk

    import os
    from glob import glob
    PATH = "/home/someuser/projects/someproject"
    EXT = "*.csv"
    all_csv_files = [file
                     for path, subdir, files in os.walk(PATH)
                     for file in glob(os.path.join(path, EXT))]
    print(all_csv_files)
    

    Copied from this blog.

提交回复
热议问题