简体   繁体   中英

How to create files inside a folder in python

I am trying to convert a pdf to image using Imagemagick and python and below are my codes

The following file takes pdf file as input from command line and converts to image

convert.py

from subprocess import check_call, CalledProcessError
from os.path import isfile

filename = sys.argv[1]

try:
    if isfile(filename):
        check_call(["convert", "-density", "150", "-trim",
                    filename, "-quality", "100", "-scene", "1", 'hello.jpg'])
except (OSError, CalledProcessError, TypeError) as e:
    print "-----{0}-----".format(e)

Above code is working fine and after running the file,my directory structure with resultant file is

codes
     convert.py
     example.pdf
     hello.jpg

But what all i want is to create the resultant image(jpg) file inside a folder with name of the pdf file like below

codes
     convert.py
     example.pdf
     example/
            hello.jpg

So can anyone please let me know how to create a directory dynamically with pdf name if not exists as above and create a jpg file like above

Use os.path.splitext to strip the file extension. Something like this:

if isfile(filename):
    dirname = os.path.splitext(filename)[0]
    if not os.path.isdir(dirname):
        os.mkdir(dirname)
    outfile = os.path.join(dirname, "hello.jpg")
    check_call(["convert", "-density", "150", "-trim",
                filename, "-quality", "100", "-scene", "1", outfile])

EDIT:

To have the new directory in the current working directory and not in the parent directory of the input file, use os.path.basename() and os.getcwd() :

dir_base = os.path.basename(os.path.splitext(filename)[0])
dirname = os.path.join(os.getcwd(), dir_base)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM