3

So I have a Python script that was given to me by a friend of mine, but I have no experience in Python. This is the code for it:

from os import path, chdir, listdir, mkdir, getcwd
from sys import argv
from zipfile import ZipFile
from time import sleep

#Defines what extensions to look for within the file (you can add more to this)
IMAGE_FILE_EXTENSIONS = ('.bmp', '.gif', '.jpg', '.jpeg', '.png', '.tif', '.tiff')

#Changes to the directory in which this script is contained
thisDir,_ = path.split(path.abspath(argv[0]))
chdir(thisDir)

#Lists all the files/folders in the directory
fileList = listdir('.')
for file in fileList:

    #Checks if the item is a file (opposed to being a folder)
    if path.isfile(file):

        #Fetches the files extension and checks if it is .docx
        _,fileExt = path.splitext(file)
        if fileExt == '.docx':

            #Creates directory for the images
            newDirectory = path.join(thisDir + "\Extracted Items", file + " - Extracted Items")
            if not path.exists(newDirectory):
                mkdir(newDirectory)

            currentFile = open(file, "r")
            for line in currentFile:
                print line

            sleep(5)



            #Opens the file as if it is a zipfile
            #Then lists the contents
            try:
                zipFileHandle = ZipFile(file)
                nameList = zipFileHandle.namelist()

                for archivedFile in nameList:
                    #Checks if the file extension is in the list defined above
                    #And if it is, it extracts the file
                    _,archiveExt = path.splitext(archivedFile)
                    if archiveExt in IMAGE_FILE_EXTENSIONS:
                        zipFileHandle.extract(archivedFile, newDirectory)
                    if path.basename(archivedFile) == "document.xml":
                        zipFileHandle.extract(archivedFile, newDirectory)
                    if path.basename(archivedFile) == "document.xml.rels":
                        zipFileHandle.extract(archivedFile, newDirectory)
            except:
                pass

For the line that reads newDirectory = path.join(thisDir + "\Extracted Items", file + " - Extracted Items")

I want to modify that to access the parent directory of thisDir and then create the \Extracted Items folder. Does anyone know what the best way to access the parent directory is in python?

2 Answers 2

2
import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PARENT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))
Sign up to request clarification or add additional context in comments.

Comments

1

You can access the parent directory using the split function from the os.path module.

from os.path import dirname, split, isdir
parent_dir = lambda x: split(x)[0] if isdir(x) else split(dirname(x))[0]

As you do not have experience in Python, a short explanation of the code:
The lambda statement defines an inline -function. Within this function, the ternary condition first evaluates if the given path x is a directory. If it applies, the path is splitted using the split function. If the path x is not a directory, first the directory name of the path is calculated and then the path is splitted.
Splitting a path looks like this: C:\Foo\Bar\file.spam => (C:\Foo\Bar\, file.spam)

Now see what's happening when calling the function:

path = r"C:\Foo\Bar\file.spam"
print "Parent directory of " + path + ":", parent_dir(path)

Parent directory of C:\Foo\Bar\file.spam: C:\Foo\

Note: In my opinion the parent directory of a file is the parent-directory of the directory of the file. If you don't define it like this, your function could also look like this:

from os.path import dirname, split, isdir
parent_dir = lambda x: split(x)[0] if isdir(x) else dirname(x)

4 Comments

So from the the originally posted code, I would not have to import anything as I already have from os import path included, correct? And as that code applies to me, would it be like parent_dir = lambda thisDir: split(thisDir)[0] if isdir(thisDir) else split(dirname(thisDir))[0] then newDirectory = path.join(parent_dir + "\Extracted Items", file + " - Extracted Items")?
Ah, so I should use parent_dir = lambda x: split(x)[0] if isdir(x) else dirname(x) as my definition of parent directory is the immediate parent directy of the folder I am currently working in?
Yes, if you only use dirname(x) you'll recieve the folder the file x is in. And yes, path is already included. If you do not import the functions directly, you can access them using the point notation. parent_dir = lambda x: path.split(x)[0] if path.isdir(x) else path.dirname(x). In your last code snipped, you need to call the function to activate it and give it the path to work on: newDirectory = path.join(parent_dir(currentDirectory), "Extracted Items", file + "- Extracted Items").
Note that path.join does automatically add \ between the arguments passed to it, so you can replace path.join(thisDir + "\Extracted Items", file, ..) with path.join(thisDir, "Extracted Items", file, ..)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.