首页 > 解决方案 > 有没有办法在 python 中找到 *.csv 存在?

问题描述

需要什么?

测试当前目录中是否生成了任何 *.csv 文件。请注意,csv 文件以日期/时间命名,因此在这种情况下无法获取文件名。

问题

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

参考

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

标签: pythonregexfilecsvexists

解决方案


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

import glob
import os.path

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

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

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

>>> 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

推荐阅读