python - 在目录和子目录中查找扩展名的文件?

标签 python

我想制作一个 Python 脚本,以根据扩展名快速将桌面上的文件组织到文件夹中。基本上,我如何使用循环获取文件、对其执行某些操作、转到下一个文件等等?

最佳答案

您需要的一切可能都包含在 os 中图书馆,更具体地说在os.path一点点和shutil一个。

要浏览目录树,您可以使用 os.walk并移动文件你可以使用 shutil.move .


编辑:我编写的一个小脚本让你继续:

import os
import shutil as sh
from collections import defaultdict

DESKTOP = '/home/mac/Desktop'

#This dictionary will contain: <extension>: <list_of_files> mappings
register = defaultdict(list)

#Populate the register
for dir_, dirs, fnames in os.walk('/home/mac/Desktop'):
    for fname in fnames:
        register[fname.rsplit('.', 1)[1]].append(os.path.join(dir_, fname))

#Iterate over the register, creating the directory and moving the files 
#with that extension in it.
for dirname, files in register.iteritems():
    dirname = os.path.join(DESKTOP, dirname)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    for file_ in files:
        sh.move(file_, dirname)

关于python - 在目录和子目录中查找扩展名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273132/

相关文章:

python - 使用日期作为输出文件中的索引

python - Pandas 根据其他列上的复合条件添加一列

python - modwsgi 和 mysql。查询仅显示触及 wsgi 文件后的实际结果

python - Python 中的时间不一致

python - django - 如何创建要在多个 View 中使用的对象(对于动态菜单)

python - 在ubuntu上安装selenium webdriver时出错,使用python3,chrome

python - 使用 "with"语句访问 Python 类方法

python - 在未先打开 ide 的情况下无法打开 .py 文件

python - 如何使用日期时间索引从pandas数据框中的特定日期选择行

Python、NLTK 无法导入 "parse_cfg"?