【问题标题】:rename files with pathlib使用 pathlib 重命名文件
【发布时间】:2021-02-13 21:19:59
【问题描述】:

我正在尝试使用不同文件夹中的其他文件的名称重命名文件夹中的文件,但我遇到了一些错误。

我要重命名的文件位于“OUT”文件夹中。我尝试使用的文件名是“IN”文件夹中的文件名。

这是我当前目录中的文件示例:

tree
├── IN
│   ├── Lost (Perdidos) 1x01 - Piloto (Parte 1).mkv
│   ├── Lost (Perdidos) 1x02 - Piloto (Parte2).mkv
│   └── Lost (Perdidos) 1x03 - Tabla Rasa.mkv
├── OUT
│   ├── 1x01 - Lost [x265].mkv
│   ├── 1x02 - Lost [x265].mkv
│   └── 1x03 - Lost [x265].mkv
├── rename.py

我正在使用的代码:

import glob
import os
from pathlib import Path


IN_DIR=Path("IN")
OUT_DIR=Path("OUT")

current_DIR = Path.cwd()
print(f"Current folder: {current_DIR}")
new_DIR = current_DIR / IN_DIR

for f1, f2 in zip(
    sorted(IN_DIR.glob("*.mkv")),
    sorted(OUT_DIR.glob("*.mkv"))): 
    os.chdir(new_DIR)
    print(f"Entering in: {Path.cwd()}")
    if f2.name[:4] in f1.name:
        print(f"{f2.name} will change to {f1.name[16:]}\n")
        old = Path(f2.name)
        print(old.is_file())
        new = Path(f1.name[16:])
        old.rename(new)
        print(f"Going back to : {os.chdir(current_DIR)}")

这是脚本的输出:

Current folder: /datos/Series/Incompletas/Lost
Entering in: /datos/Series/Incompletas/Lost/IN
1x01 - Lost [x265].mkv will change to 1x01 - Piloto (Parte 1).mkv

Old name: 1x01 - Lost [x265].mkv
False
New name: 1x01 - Piloto (Parte 1).mkv
Traceback (most recent call last):
  File "rename.py", line 28, in <module>
    old.rename(new)
  File "/usr/lib/python3.8/pathlib.py", line 1361, in rename
    self._accessor.rename(self, target)
FileNotFoundError: [Errno 2] No such file or directory: '1x01 - Lost [x265].mkv' -> '1x01 - Piloto (Parte 1).mkv'

我真的很困惑,因为我正在访问文件所在的文件夹,但看起来文件不存在。

[更新] 看起来我试图访问的文件不是文件。因此,我遇到了错误。

【问题讨论】:

  • 评论#os.chdir(new_DIR)并尝试
  • 和以前一样的错误。我已经更新了原帖

标签: python file-rename pathlib


【解决方案1】:

您的问题是您仅指定 os.rename() 函数的文件名,但当前目录不是包含这些文件的 OUT 目录。最好的做法是将输出目录添加到重命名涉及的两个路径中,以便您可以从您所在的目录进行调用:

import glob
import os
from pathlib import Path


IN_DIR=Path("IN")
OUT_DIR=Path("OUT")

current_DIR = Path.cwd()
print(f"Current folder: {current_DIR}")
new_DIR = current_DIR / IN_DIR

for f1, f2 in zip(
    sorted(IN_DIR.glob("*.mkv")),
    sorted(OUT_DIR.glob("*.mkv"))): 
    if f2.name[:4] in f1.name:
        old = OUT_DIR.joinpath(f2.name)
        new = OUT_DIR.joinpath(f1.name[16:])
        print("{} ===> {}".format(old, new))
        old.rename(new)

运行后 OUT 中的文件名:

1x01 - Piloto (Parte 1).mkv
1x02 - Piloto (Parte 2).mkv
1x03 - Tabla Rasa.mkv

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 2016-05-29
    • 2019-12-28
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多