如何根据文件扩展名组织文件系统

时间:2019-11-21 19:10:13

标签: python-3.x filesystems

我是python编程的新手,我正在学习编写一个程序来根据文件的扩展名来组织文件,例如,系统将提示用户输入路径,然后程序将遍历给定的路径并进行组织给定路径中的文件扩展名。

ext = ext[1:] #store extension type行中,当文件名太长时,我无法检测到文件扩展名。

我尝试更改索引值以查看是否可以获得不同的结果。例如,对于live_video.mp4,我希望代码从文件名中提取.mp4

try:
    print("Enter directory  or the folder path")
    path = input("Format: C:\\")
    os.path.join(path)
    lst = os.listdir(path)

    for f in lst:  # Iterate through each and every file
        ext = os.path.split(f)
        ext = ext[1:]  # store extension type

        if ext == '':  # Continue to next iteration if its a directory
            continue
        if os.path.exists(path + '/' + ext):  # Move the file to the directory where the name 'ext' already existsenter code here
           shutil.move(path + '/' + f, path + '/' + ext + '/' + f)

1 个答案:

答案 0 :(得分:0)

首先通过运行安装pytest-shutil python库 pip install pytest-shutil(如果尚未安装)。

import os
import shutil

try:
    print("Enter directory  or the folder path")
    path = input("Format: C:\\")
    list_ = os.listdir(path)

    for file_ in list_:
        name, ext = os.path.splitext(file_)

        ext = ext[1:]
        if ext == '':
            continue

        if os.path.exists(path + '/' + ext):
            shutil.move(path + '/' + file_, path + '/' + ext + '/' + file_)

        else:
            os.makedirs(path + '/' + ext)
            shutil.move(path + '/' + file_, path + '/' + ext + '/' + file_)
except:
    print('error to throw')