Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pathlib path object not converting to string [duplicate]

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()
like image 289
MrClean Avatar asked Jun 01 '17 19:06

MrClean


People also ask

How do I change a string to a PosixPath?

Unsupported operand type(s) for +: 'PosixPath' and 'str' # The Python "Unsupported operand type(s) for +: 'PosixPath' and 'str'" occurs when we try to use the addition (+) operator with a PosixPath object and a string. To solve the error, use the str() class to convert the path object to a string.

What does Pathlib path do in Python?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

How does the Pathlib module represent paths?

path module is replaced by the Path class of Pathlib module that represents the path by chaining methods and attributes. The clever overloading of the / operator makes the code readable and easy to maintain.


1 Answers

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.

like image 166
Aran-Fey Avatar answered Oct 14 '22 02:10

Aran-Fey