使用Python查找目录中的所有CSV文件

min*_*een 40 file-upload python-2.7

如何在python中找到扩展名为.csv的目录中的所有文件?

tcp*_*008 63

import os
import glob

path = 'c:\\'
extension = 'csv'
os.chdir(path)
result = glob.glob('*.{}'.format(extension))
print(result)
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法在不更改目录的情况下做到这一点?我们不能将目录指定为 glob 命令本身的一部分吗? (4认同)
  • 这是一个简短的解决方案,但请注意,这仅扫描当前目录(运行脚本的位置)。要更改使用 `os.chdir("/mydir")`,如此处提供的:http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in- Python (3认同)
  • @ppasler嗨,用你的消化编辑的答案.另外我觉得现在它更加pythonic :) (2认同)

Ber*_*ler 30

from os import listdir

def find_csv_filenames( path_to_dir, suffix=".csv" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]
Run Code Online (Sandbox Code Playgroud)

该函数find_csv_filenames()返回一个文件名列表作为字符串,它们驻留在path_to_dir具有给定后缀的目录中(默认情况下为".csv").

附录

如何打印文件名:

filenames = find_csv_filenames("my/directory")
for name in filenames:
  print name
Run Code Online (Sandbox Code Playgroud)


The*_* PR 14

通过使用过滤器和 lambda 的组合,您可以轻松过滤掉给定文件夹中的 csv 文件。

import os

all_files = os.listdir("/path-to-dir")    
csv_files = list(filter(lambda f: f.endswith('.csv'), files))

# lambda returns True if filename name ends with .csv or else False
# and filter function uses the returned boolean value to filter .csv files from list files.
Run Code Online (Sandbox Code Playgroud)


Raj*_*rma 6

使用Python OS模块在目录中查找csv文件.

这里有一个简单的例子:

import os

# This is the path where you want to search
path = r'd:'

# this is the extension you want to detect
extension = '.csv'

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file
Run Code Online (Sandbox Code Playgroud)


rs7*_*s77 5

我必须获取csv子目录中的文件,因此,使用来自tchlpr的响应,我对其进行了修改以使其最适合我的用例:

import os
import glob

os.chdir( '/path/to/main/dir' )
result = glob.glob( '*/**.csv' )
print( result )
Run Code Online (Sandbox Code Playgroud)