【问题标题】:Is there a way to scan a directory to see how many files of certain type there is?有没有办法扫描目录以查看有多少特定类型的文件?
【发布时间】:2020-07-30 23:23:03
【问题描述】:
所以,如果我有一个像下面这样的目录,有没有办法扫描多少个文件名中带有特定代码的文件。例如,如果我想要以下目录中以 17042020 开头的文件数为 6?
1704202001-01.csv
1704202001-02.csv
1704202002-01.csv
1704202002-02.csv
1704202003-01.csv
1704202003-02.csv
001.png
002.pdf
003.docx
004.jpg
【问题讨论】:
标签:
python
python-3.x
pandas
csv
operating-system
【解决方案1】:
您可以使用pathlib 模块或简单的glob:
from pathlib import Path
folder = Path(dir_of_files)
specific_files = list(folder.glob('1704202001-*.csv')
#or : list(folder.rglob('1704202001-*.csv') ... this will recursively search thru every subfolder for files that match this
print(specific_files)
【解决方案2】:
使用 os 获取文件列表:
import os
list = os.listdir("path")
for element in list:
if yourconditions:
print(element)
【解决方案3】:
在 Unix/Linux/macOS(您的操作系统也是如此)上,您可以在 shell 中以多种方式完成此操作。
假设你在指定的文件夹中,你可以这样做:
ls | grep "1704202001" | wc | awk '{print $1}'
ls 将列出您的文件夹文件/子文件夹
grep 将仅使用包含您的模式的行过滤您的搜索
wc 将计算搜索的行数/字符数
awk 将被告知只打印第一列(wc 将回答 3 个数字,只有第一个对我们感兴趣)
如果你想要一些递归搜索,你可以使用find
find . -name "*1704202001*" | wc | awk '{print $1}'
find 将在 . 和所有子文件夹中搜索 RegExp 模式(因此我们使用通配符 * 来匹配完整文件名中的模式)。
最后但不是列表,您可能想计算有多少文件包含您的模式(不是在名称中,而是在文件本身中)。你可以使用grep:
grep -R "1704202001" | wc | awk '{print $1}'
您要求的是 Python,但也要求 操作系统帮助,这个答案是最后一个 :)
希望对你们中的一些人有所帮助。
【解决方案4】:
使用现在最适合路径的pathlib 模块
import pathlib
from typing import List
"""!
@brief Finds files with the given unique code in name in directory
@param[in] directory pathlib.Path directory of searching
@param[in] unique_code str code in the filename
@return List[pathlib.Path] list of filepaths with unique code in name
"""
def find_files(directory:pathlib.Path, unique_code:str) -> List[pathlib.Path]:
result:List[pathlib.path] = list()
for filepath in directory.glob('*'):
if filepath.is_file() and unique_code in filepath.name:
result.append(filepath)
return result
# Set Your directory!
directory:pathlib.Path = pathlib.Path('your/dir')
unique_code:str = '17042020'
found_files:List[pathlib.Path] = find_files(directory, unique_code)
print(f"Found files with unique code [{unique_code}]: {len(found_files)}")
for filepath in found_files:
print(f" {filepath.resolve()}")