python 基于扩展移动文件? [英] python moving files based on extensions?

查看:36
本文介绍了python 基于扩展移动文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何改进这个 Python 代码.我想在这里添加一个包含所有扩展名的列表,并在列表的帮助下搜索src"目录中的扩展名并将它们移动到目的地.

How can I improve this python code. I want to add a list here which includes all the extension and with the help of the list, I want to search for "src" directory for extensions and move them to the destination.

import shutil
import glob
import os

dest_dir = "/home/xxxx/Software/"
dest_dir2 = "/home/flyingpizza/Pictures/"

for file in glob.glob(r'/home/xxxxx/Downloads/*.pdf'):
    print (file)
    shutil.move(file,dest_dir)

for file in glob.glob(r'/home/xxxx/Downloads/*.docx'):
    print(file)
    shutil.move(file, dest_dir)

for file in glob.glob(r'/home/xxxx/Downloads/*.exe'):
    print(file)
    shutil.move(file,dest_dir)

for file in glob.glob(r'/home/xxxx/Downloads/*.jpg'):
    print(file)
    shutil.move(file,dest_dir2)

for file in glob.glob(r'/home/xxxxx/Downloads/*.torrent'):
    print(file)
    os.remove(file)

推荐答案

我会使用位置和扩展名的字典,例如 {'/home/xxx/Pictures': ['jpg','png','gif'], ...} 我使用键"作为目的地,值是每个目的地的扩展名列表.

I would use a dict of locations and extensions, for example {'/home/xxx/Pictures': ['jpg','png','gif'], ...} Where I use the "keys" as destinations and the values are lists of extensions for each destination.

source = '/home/xxx/randomdir/'
mydict = {
    '/home/xxx/Pictures': ['jpg','png','gif'],
    '/home/xxx/Documents': ['doc','docx','pdf','xls']
}
for destination, extensions in mydict.items():
    for ext in extensions:
        for file in glob.glob(source + '*.' + ext):
            print(file)
            shutil.move(file, destination)

虽然 Fabre 的解决方案很好,但您必须为每个目标文件夹重复他的双循环解决方案,而在这里,只要给它一个适当的 dict

While Fabre's solution is good, you would have to repeat his double-loop solution for every destination folder, whereas here you have a triple-loop that does everything, as long as you give it a proper dict

还有一句忠告,如果您编写的代码看起来如此重复,就像您的一样,请确保有一种方法可以使其更简单,无论是使用循环还是带参数的函数.

Also a word of advice, if you write code that looks so repetitive, like yours do, be sure there is a way to make it simpler, either with a loop or a function that takes arguments.

这篇关于python 基于扩展移动文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆