查找Python中缺少.csv文件的目录
我有大约1000个目录,其中包含各种查找Python中缺少.csv文件的目录,python,python-3.x,Python,Python 3.x,我有大约1000个目录,其中包含各种.csv文件。我试图检查每个目录中是否存在特定类型的csv文件,其中包含以PTSD\u OCOTBER开头的文件名 如果该目录中不存在该文件,我想将该目录打印成.txt文件 这是我到目前为止所拥有的 import os,sys,time,shutil import subprocess #determine filetype to look for. file_type = ".csv" print("Running fil
.csv
文件。我试图检查每个目录中是否存在特定类型的csv文件,其中包含以PTSD\u OCOTBER
开头的文件名
如果该目录中不存在该文件,我想将该目录打印成.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
文件,但如何实现上述目标?因此文件是您当前正在浏览的目录中的文件列表。您想知道是否没有以PTSD\u OCOTBER
开头的文件(PTSD\u-OCOTBER
):
现在要将结果保存到文本文件中吗?如果您有Unix风格的计算机,则可以在终端上使用输出重定向,例如
python3 fileanalysis.py > result.txt
在写入后,打印(文件夹名称)
而不是,使用文件夹名称执行操作
也可以使用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))
您已经有了可用的文件夹\u name
变量,您可以使用带有open(“dirs.txt”,“w”)的作为fileptr:
并使用fileptr.write(文件夹\u name+“\n”)
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))