[英]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:变化:
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.