python - 有没有办法在 python 中找到 *.csv 存在?
问题描述
需要什么?
测试当前目录中是否生成了任何 *.csv 文件。请注意,csv 文件以日期/时间命名,因此在这种情况下无法获取文件名。
问题
尝试了 os.path.isfile([exact_path_to_file]) 并且它有效。然而,我们需要找到的是,如果生成了任何一个 .csv 文件,则 assertTrue 否则 assertFalse。在 assertTrue 的情况下,将删除文件。这可以用python吗?
参考
最接近的是使用像这篇文章这样的正则表达式,但是对于这个简单的检查,真的需要使用正则表达式吗?
解决方案
使用该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
推荐阅读
- python - 将 Keras 模型导出到具有 (None, 2) 输出形状的 protobuf
- json - JsonSerializer.Serialize vs JsonResult - 一个可能的对象循环.NET Core 3.1
- javascript - 如何在echarts中显示其他小数点(角度)
- jasmine - 有什么方法可以验证不是每次都出现的动态弹窗
- mongodb - 如何在mongo中进行索引后findOneAndUpdate()的性能评估
- php - Laravel 5.8 - in_array 给我错误:'htmlspecialchars() 期望参数 1 是字符串,给定数组'
- oauth-2.0 - 在OAuth2中,当执行刷新令牌请求检索新的访问令牌时,之前的访问令牌是否失效?
- python - 无法解析嵌套字符串模板
- sql - 如何使用上面的总和更新每个 fatura_id 的 valor_total
- python - 显示数据帧 Tkinter 子集的下拉选项