Python Pathlib路径对象无法转换为字符串。

60

我正在尝试使用Shutil和Pathlib组合复制一个pdf文件,但是当我运行代码时,我遇到了错误信息"str object is not callable"。这个错误是由于使用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()
1个回答

96

问题就在这里:

str = str(pdf.stem)

您正在覆盖值str,因此从循环的第二次迭代开始,str不再引用内置的str函数。请为此变量选择一个不同的名称。


5
无论如何,Path.stem返回一个str对象,因此您可以通过执行以下操作进一步简化:split = pdf.stem.split('_') - Philip Ridout
4
请勿使用内置函数 https://docs.python.org/3/library/functions.html 作为任何对象的命名空间。 - hussam
47
您可以使用Path(path_here).as_posix()来实现相同的功能。 - Prayson W. Daniel
最好为此编写一个小型函数。因为如果变量路径为None或其他类型:str()将始终返回该变量的强制转换,如“None”。解决方案是:def path_object_to_str(obj): if isinstance(obj, pathlib.Path): return str(obj) - Ilyas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接