有没有办法找到 python 中存在的 *.csv?

Is there a way to find *.csv exists in python?

需要什么?

测试当前目录下是否生成*.csv文件。请注意,csv 文件以 date/time 命名,因此在这种情况下无法获取文件名。

问题

尝试了 os.path.isfile([exact_path_to_file]) 并且有效。然而,我们需要找到的是,如果生成了任何一个 .csv 文件,则 assertTrue 否则 assertFalse。在 assertTrue 的情况下,将删除该文件。 python 这可能吗?

参考

最接近的是使用像 this post 这样的正则表达式,但是对于这个简单的检查,真的需要使用正则表达式吗?

使用 glob module 列出与模式匹配的目录中的文件:

import glob
import os.path

csv_files = glob.glob(os.path.join(directory_name, '*.csv'))

如果csv_files是一个非空列表,则有匹配的文件。

在后台,glob 模块为您将 glob 模式转换为正则表达式(通过 fnmatch.translate(),在给定目录上运行 os.listdir(),并且 returns 只有那些与模式匹配的名称,作为完整路径:

>>> import os.path, glob, tempfile
>>> with tempfile.TemporaryDirectory() as directory_name:
...     pattern = os.path.join(directory_name, '*.csv')
...     # nothing in the directory, empty glob
...     print('CSV file count:', len(glob.glob(pattern)))
...     # create some files
...     for n in ('foo.csv', 'bar.txt', 'ham.csv', 'spam.png'):
...         __ = open(os.path.join(directory_name, n), 'w')  # touches file, creating it
...     csv_files = glob.glob(pattern)
...     print('CSV file count after creation:', len(csv_files))
...     for filename in csv_files:
...         print(filename)
...
CSV file count: 0
CSV file count after creation: 2
/var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmp2vttt0qf/foo.csv
/var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmp2vttt0qf/ham.csv

您可以使用 os.listdir 获取所有文件名,使用 os.path.splitext 获取文件扩展名

any(os.path.splitext(f)[1] == '.csv' for f in os.listdir(path))

对于当前路径,path=os.getcwd()path='.'都可以(甚至可以省略参数)。要删除所有 *.csv 文件,只需执行一个循环

for f in os.listdir('.'):
    if os.path.splitext(f)[1] == '.csv':
        os.remove(f)