【问题标题】:Renaming files in a folder with pathlib and for loops使用 pathlib 和 for 循环重命名文件夹中的文件
【发布时间】:2020-08-25 14:21:07
【问题描述】:

我已经用 Python 编写了以下重命名工具。在我在 for 循环中添加 os.chdir 之前,它无意中将我的所有文件都移动到了一个目录中,这使它工作得更好,并将每个重命名的文件保存在其正确的文件夹中。但是我真的不明白为什么这个脚本(没有 os.chdir)将我的所有文件移动到一个目录背后的逻辑,有人可以帮我理解吗?谢谢。

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

【问题讨论】:

    标签: python path rename pathlib chdir


    【解决方案1】:

    我认为这是因为它将文件重命名为您当前的工作目录(即您保存脚本的位置),而不是存储文件的实际目录。

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

    该脚本是为此在您的 cwd 中创建一个名为“文件”的文件夹。通过添加 chdir(f),它会在这个目录中创建,而不是因为它已经存在,它会修改现有文件。这就是你想要的。

    我可能错了,但这是我的理解。我希望这是有道理的。

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 2021-02-13
      • 1970-01-01
      • 2022-06-27
      • 2015-10-22
      • 1970-01-01
      • 2021-10-23
      • 2021-01-22
      • 2016-12-18
      相关资源
      最近更新 更多