python - 在 Python 中查找缺少 .csv 文件的目录
问题描述
我有大约 1000 个目录,其中包含各种.csv
文件。我正在尝试检查PTSD_OCOTBER
每个目录中是否存在包含以 开头的文件名的特定类型的 csv 文件。
如果目录中不存在此文件,我想将该目录打印到 .txt 文件中。
这是我到目前为止所拥有的。
import os,sys,time,shutil
import subprocess
#determine filetype to look for.
file_type = ".csv"
print("Running file counter for" + repr(file_type))
#for each folder in the root directory
for subdir, dirs, files in os.walk(rootdir):
if("GeneSet" in subdir):
folder_name = subdir.rsplit('/', 1)[-1] #get the folder name.
for f in files:
#unclear how to write this part.
#how to tell if no files exist in directory?
这成功地找到了.csv
感兴趣的文件,但是如何实现上述目标呢?
解决方案
files
您当前正在浏览的该目录中的文件列表也是如此。您想知道是否没有以PTSD_OCOTBER
( PTSD_OCTOBER
?) 开头的文件:
for subdir, dirs, files in os.walk(rootdir):
if("GeneSet" in subdir):
folder_name = subdir.rsplit('/', 1)[-1] #get the folder name.
dir_of_interest = not any(f.startswith('PTSD_OCOTBER') for f in files)
if dir_of_interest:
# do stuff with folder_name
现在您想将结果保存到文本文件中吗?如果您有一台 Unix 风格的计算机,那么您可以在终端上使用输出重定向,例如
python3 fileanalysis.py > result.txt
在写print(folder_name)
而不是# do stuff with folder_name
.
或者你可以使用 Python 本身来编写文件,例如:
found_dirs = []
for subdir, dirs, files in os.walk(rootdir):
...
if dir_of_interest:
found_dirs.append(folder_name)
with open('result.txt', 'w') as f:
f.write('\n'.join(found_dirs))
推荐阅读
- common-lisp - 无差别地循环遍历数组或列表
- c++ - 在运行时在 C++ 中创建包装器方法 - 已知原型
- javascript - Webpack:未生成预期的捆绑包
- javascript - 在 javascript 类的另一个函数中调用一个函数
- matlab - 如何在没有 for 循环的情况下表达如此大量的计算?
- wordpress - Wordpress:wp_hash_password 未按预期工作。所有登录失败
- android - Android 是否可以为单个请求记录每个客户端-服务器连接?
- javascript - 我的提示不会返回字符串,它只返回 NaN
- android - CircleCI 2.0 Android 构建总是失败
- git - 推送分支时的 Github 拉取请求链接