58

I am trying to use Shutil to copy a pdf file using path objects from Pathlib, however when I run my code I get the error "str object is not callable" when converting my paths back to strings using str(). Any explanation for why this is occurring would be very helpful. Thanks!

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()
MrClean
  • 1,300
  • 2
  • 12
  • 17

1 Answers1

93

The problem is here:

str = str(pdf.stem)

You're overwriting the value str, so starting from the 2nd iteration of your loop, str no longer refers to the built-in str function. Choose a different name for this variable.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 5
    Path.stem returns a str object anyway, so you could simplify this further by doing: split = pdf.stem.split('_') – Philip Ridout Jun 05 '17 at 09:29
  • 4
    refrain from using built-in functions https://docs.python.org/3/library/functions.html as namespaces for any objects. – hussam Feb 12 '21 at 01:43
  • 44
    You can also do `Path(path_here).as_posix()` – Prayson W. Daniel Oct 14 '21 at 06:44
  • it is better to write a mini-function for that. Because if the variable path is None or another type: the str() will return always the cast of that variable like ‘None’. The solution is: `# def path_object_to_str(obj): if isinstance(obj, pathlib.Path): return str(obj) ` – Ilyas Dec 09 '22 at 15:13