根据文件名将文件组织到文件夹中

时间:2018-05-26 03:01:13

标签: python python-3.x

我试图创建一个读取pdf文件的程序(例如files.pdf),按名称分隔它们并将它们移动到相关文件夹(基于名称),如下所示:

Files:
house.pdf
house_blue.pdf
road.pdf

Folders:
house = house.pdf, house_blue.pdf
road  = road.pdf

我的代码:

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if len(file_name.split('_')) == 2:
        f_name, f_course = file_name.split('_')
    elif len(file_name.split('_')) != 2:
        f_name = file_name

def movefile (file_name):
    new_dir =  src + "/" + file_name
    for file_name in os.listdir():
        if not os.path.exists(new_dir):
            os.mkdir(new_dir)
        if file_name.startswith(file_name):
            shutil.move(src+"/"+file_name, new_dir)

它工作正常,唯一的问题是for语句只导致最后一个pdf文件,只创建一个文件夹并将所有文件复制到该文件夹​​。

有人可以在错误的地方帮助我吗?

提前致谢。

编辑: 代码工作:

src = (os.getcwd())

for f in os.walk(src):
    for f in os.listdir(src):
        if os.path.isfile(src): #Checar se possui arquivos dentro da   pasta(src).
            continue
        lfolders = os.listdir(src) #Atribuir na variavel lfolders todos os diretórios na pasta (src).
        file_name, file_ext = os.path.splitext(f) #separar nome da extensão (.pdf)
        if len(file_name.split('_')) == 2: #se possuir dois nomes (nome e curso)
            f_name, f_course = file_name.split('_')
            try:
                if f_name not in lfolders:
                    for dirmake in os.listdir(src):
                        os.makedirs(os.path.join(src, f_name))
                elif f_name in lfolders:
                    shutil.move(f, src+"/"+f_name)
            except OSError:
                pass

        elif len(file_name.split(')')) != 2: #se possuir um nome (nome)
            f_name = file_name
            try:
                if f_name not in lfolders:
                    for dirmake in os.listdir(src):
                        os.makedirs(os.path.join(src, f_name))
                elif f_name in lfolders:
                    shutil.move(f, src+"/"+f_name)
            except OSError:
                pass

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要为循环的每次迭代做一些事情

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == 'pdf':
        if len(file_name.split('_')) == 2:
            folder, f_course = file_name.split('_')
        elif len(file_name.split('_')) != 2:
            folder = file_name
    print("Ready to move {} into folder {}".format(file_name, folder)) 
    movefile(f, folder)  # Call your function, add a parameter for the folder