Python Pathlib路径对象未转换为字符串

标签 python shutil pathlib

这个问题在这里已经有了答案:





I'm getting "TypeError: 'list' object is not callable". How do I fix this error? [duplicate]

(2 个回答)


3年前关闭。




我正在尝试使用 Shutil 使用来自 Pathlib 的路径对象复制 pdf 文件,但是当我运行我的代码时,我收到错误“str 对象不可调用”
使用 str() 将我的路径转换回字符串时。任何关于为什么会发生这种情况的解释都会非常有帮助。谢谢!

from pathlib import Path
from wand.image import Image as wandImage
import shutil
import sys
import os

def pdf2Jpeg(pdf_path):
    pdf = pdf_path
    jpg = pdf[:-3] + "jpg"
    img = wandImage(filename=pdf)
    img.save(filename=jpg)

src0 = Path(r"G:\Well Schematics\Well Histories\Merged")
dst0 = Path(r"G:\Well Schematics\Well Histories\Out")
if not dst0.exists():
    dst0.mkdir()

pdfs = []
api = ''
name = ''
pnum = ''
imgs = []

for pdf in src0.iterdir():
    pdfs.append(pdf)

for pdf in pdfs:

    if not dst0.exists():
        dst0.mkdir()

    str = str(pdf.stem)
    split = str.split('_')
    api = split[0]
    name = split[1]
    pnum = split[2]

    shutil.copy(str(pdf), str(dst0))
    for file in dst0.iterdir():
        newpdf = file
    pdf2Jpeg(str(newpdf))
    newpdf.unlink()

最佳答案

问题在这里:

str = str(pdf.stem)

您正在覆盖值 str ,所以从循环的第二次迭代开始,str不再指内置str功能。为此变量选择一个不同的名称。

关于Python Pathlib路径对象未转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315815/

相关文章:

python-3.x - python : move a file up one directory

python - 在新的 Python 版本上安装 Python 模块

python - 使用 python 子进程将文件从 .sam 转换为 .bam

python,寻找,讲述,阅读。从巨大的 csv 文件中读取行

python - 使用 ID 连接特定列上的 2 个数据框

python - shutil.move IOError : [Errno 2] - When in loop

python - 有效使用python shutil copy2

python - 将文件移动到子目录时出现 os.rename 路径错误

python - 什么时候应该使用 pathlib.Path.mkdir() 与 os.mkdir() 或 os.makedirs()?