Find all CSV files in a directory using Python

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

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

相关标签:
11条回答
  • 2020-12-02 18:38
    import os
    
    path = 'C:/Users/Shashank/Desktop/'
    os.chdir(path)
    
    for p,n,f in os.walk(os.getcwd()):
        for a in f:
            a = str(a)
            if a.endswith('.csv'):
                print(a)
                print(p)
    

    This will help to identify path also of these csv files

    0 讨论(0)
  • 2020-12-02 18:47

    You could just use glob.glob with recursive = true, the pattern ** will match any files and zero or more directories, subdirectories and symbolic links to directories.

    import glob, os
    
    os.chdir("C:\\Users\\username\\Desktop\\MAIN_DIRECTORY")
    
    for file in glob.glob("*/.csv", recursive = true):
        print(file)
    
    0 讨论(0)
  • 2020-12-02 18:53

    I had to get csv files that were in subdirectories, therefore, using the response from tchlpr I modified it to work best for my use case:

    import os
    import glob
    
    os.chdir( '/path/to/main/dir' )
    result = glob.glob( '*/**.csv' )
    print( result )
    
    0 讨论(0)
  • 2020-12-02 18:58
    import os
    import glob
    
    path = 'c:\\'
    extension = 'csv'
    os.chdir(path)
    result = glob.glob('*.{}'.format(extension))
    print(result)
    
    0 讨论(0)
  • 2020-12-02 18:58

    This solution uses the python function filter. This function creates a list of elements for which a function returns true. In this case, the anonymous function used is partial matching '.csv' on every element of the directory files list obtained with os.listdir('the path i want to look in')

    import os
    
    filepath= 'filepath_to_my_CSVs'  # for example: './my_data/'
    
    list(filter(lambda x: '.csv' in x, os.listdir('filepath_to_my_CSVs')))
    
    0 讨论(0)
提交回复
热议问题