【问题标题】:How to Access Parent Directory in Python如何在 Python 中访问父目录
【发布时间】:2011-10-25 04:24:13
【问题描述】:

所以我有一个 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 中访问父目录的最佳方式是什么?

【问题讨论】:

    标签: python path directory parent traversal


    【解决方案1】:
    import os.path,sys
    CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
    PARENT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))
    

    【讨论】:

      【解决方案2】:

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

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

      由于你没有Python经验,简单解释一下代码:
      lambda 语句定义了一个 inline 函数。在此函数中,三元条件首先评估给定路径 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)
      

      【讨论】:

      • 所以从最初发布的代码中,我不必导入任何东西,因为我已经包含了from os import path,对吗?由于该代码适用于我,会不会是 parent_dir = lambda thisDir: split(thisDir)[0] if isdir(thisDir) else split(dirname(thisDir))[0] 然后是 newDirectory = path.join(parent_dir + "\Extracted Items", file + " - Extracted Items")
      • 啊,所以我应该使用parent_dir = lambda x: split(x)[0] if isdir(x) else dirname(x),因为我对父目录的定义是我当前工作的文件夹的直接父目录?
      • 是的,如果您只使用dirname(x),您将收到文件x 所在的文件夹。是的,路径已经包含在内。如果不直接导入函数,可以使用 point notation 访问它们。 parent_dir = lambda x: path.split(x)[0] if path.isdir(x) else path.dirname(x)。在您最后截取的代码中,您需要调用函数来激活它并为其提供工作路径:newDirectory = path.join(parent_dir(currentDirectory), "Extracted Items", file + "- Extracted Items").
      • 请注意path.join 会在传递给它的参数之间自动添加\ ,因此您可以将path.join(thisDir + "\Extracted Items", file, ..) 替换为path.join(thisDir, "Extracted Items", file, ..)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2023-03-30
      • 2012-07-27
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多