首页 > 解决方案 > 在 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感兴趣的文件,但是如何实现上述目标呢?

标签: pythonpython-3.x

解决方案


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

推荐阅读