简体   繁体   English

将文件移动到其对应的文件夹

[英]Move files to its corresponding folders

How can I move every file to its corresponding folder?如何将每个文件移动到其相应的文件夹? I managed to create a folder depending on the title of the file.我设法根据文件的标题创建了一个文件夹。 Now I want to move every file to its folder.现在我想将每个文件移动到它的文件夹中。

My code:我的代码:

import os 
directorio=list(os.listdir())

pdfs=[]

for i in directorio: 
  if i.endswith('.pdf'):
    pdfs.append(i)
  
#with this step we create different folders for each group of files 
for i in range(len(pdfs)):

  folder=pdfs[i].split('#')[1].split('.')[0]

  try:
    folder=os.mkdir(folder)
  except:
    pass

在此处输入图像描述

Here's a cleaned up version of your original code which moves as well.这是您的原始代码的清理版本,它也会移动。 Note that I have used pathlib.Path rather than the old os.path api.请注意,我使用的pathlib.Path而不是旧的os.path api。

from pathlib import Path

for pdf in Path(".").glob("*.pdf"):
    dir = pdf.parent / pdf.stem.split("#")[-1]
    dir.mkdir(exist_ok=True)
    pdf.rename(dir / pdf.name)

Changes:变化:

  • use glob.使用全球。 But listdir and manual filtering also works但是 listdir 和手动过滤也可以
  • don't cast to list不要列出
  • move straight after making the dir, since that's what we want the dir for, and we know it at the moment!制作目录后直接移动,因为这就是我们想要目录的目的,我们现在知道了!

exist_ok causes mkdir to continue if the directory is already present, rather than throwing an error.如果目录已经存在, exist_ok会导致 mkdir 继续,而不是抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM