简体   繁体   English

使用 pathlib 和 for 循环重命名文件夹中的文件

[英]Renaming files in a folder with pathlib and for loops

I've written the following renaming tool in Python.我已经用 Python 编写了以下重命名工具。 It was unintentionally moving all my files to a single directory until I added the os.chdir in my for loop, which then made it work better and keep each renamed file inside its correct folder.它无意中将我的所有文件移动到一个目录中,直到我在 for 循环中添加了 os.chdir,然后使它更好地工作并将每个重命名的文件保存在其正确的文件夹中。 But I don't really understand the logic behind why this script, without the os.chdir, was moving all my files to a single directory, can somebody help me understand?但是我真的不明白为什么这个脚本没有 os.chdir 将我的所有文件移动到一个目录背后的逻辑,有人可以帮助我理解吗? Thank you.谢谢你。

import pathlib
from pathlib import Path
import os

folderDir = Path(input("Please enter the parent directory: \n"))

folderList = [folder for folder in folderDir.iterdir() if folder.is_dir()]

for f in folderList:
    
    fileList = [e for e in f.iterdir() if e.is_file()]

    os.chdir(f)

    count = 1
    for i in fileList:
        folderName = os.path.basename(os.path.dirname(i))
        i.rename(folderName + "_" + str(count).zfill(3) + pathlib.Path(i).suffix)
        count += 1

I would assume this is because it was renaming the files to your current working directory (ie wherever you saved the script) rather than the actual directory where the files were stored.我认为这是因为它将文件重命名为您当前的工作目录(即您保存脚本的位置)而不是存储文件的实际目录。

file = your/file/name.txt
os.path.dirname(file) # This gives 'your/file'
os.path.basename(your/file) # This gives 'file'

The script was therefor creating a folder called 'file' in the example above in your cwd.该脚本用于在上面的示例中在您的 cwd 中创建一个名为“file”的文件夹。 By adding in the chdir(f), it creates in this directory instead as this already exists it modifies the existing file.通过添加 chdir(f),它会在此目录中创建,因为它已经存在,它会修改现有文件。 Which is what you want.这就是你想要的。

I may be wrong but that it is my understanding.我可能错了,但这是我的理解。 I hope this makes sense.我希望这是有道理的。

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

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