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

标签 python regex file csv exists

需要什么?

测试当前目录下是否生成*.csv文件。请注意,csv 文件是以日期/时间命名的,因此在这种情况下不可能获取文件名。

问题

尝试了 os.path.isfile([exact_path_to_file]) 并且它有效。然而,我们需要找到的是是否生成了任何一个 .csv 文件(如果是),则为断言 True,否则为断言 False。如果assertTrue,将删除该文件。 这可以用Python实现吗?

引用

最接近的是使用正则表达式,如 this然而,对于这个简单的检查,是否真的需要使用正则表达式?

最佳答案

使用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() ,并仅返回那些与模式匹配的名称,作为完整路径:

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

关于python - 有没有办法找到Python中存在*.csv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367594/

相关文章:

python - 从列表的每个元素中获取子字符串

regex - 使用替换转义反斜杠时遇到问题

c++从二进制文件中读取整数,缺少一些数据

iphone - 从 iPhone 应用程序导入 native 日历的可能性

javascript - 单击按钮时用用户选择的图像填充 div

python - Pandas Column Multiindex 相互减去列

python - 为什么我的传奇在Python中不动

python - 不同的 :maxdepth: for specific entries in toctree (Sphinx)

regex - Google Analytics(分析)目标跟踪的正则表达式匹配

regex - 需要识别邮政编码范围