如何在Python中访问父目录

时间:2011-08-11 16:53:48

标签: python path directory parent traversal

所以我有一个由我的朋友给我的Python脚本,但我没有使用Python的经验。这是它的代码:

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

对于标有newDirectory = path.join(thisDir + "\Extracted Items", file + " - Extracted Items")

的行

我想修改它以访问thisDir的父目录,然后创建\Extracted Items文件夹。有谁知道访问父目录的最佳方法是在python中?

2 个答案:

答案 0 :(得分:2)

import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PARENT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))

答案 1 :(得分:1)

您可以使用split模块中的os.path功能访问父目录。

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

由于您没有Python经验,因此对代码进行简短说明:
lambda语句定义了内联函数。在此函数中,三元条件首先评估给定路径x是否是目录。如果适用,则使用split函数拆分路径。如果路径x 不是目录,则首先计算路径的目录名称,然后分割路径。
拆分路径如下所示:C:\Foo\Bar\file.spam => (C:\Foo\Bar\, file.spam)

现在看看调用函数时发生了什么:

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

C:\ Foo \ Bar \ file.spam:C:\ Foo \

的父目录

注意:在我看来,文件的父目录是文件目录的父目录。如果你没有像这样定义它,你的函数也可能如下所示:

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