如何在Python中访问父目录

3 投票
2 回答
3752 浏览
提问于 2025-04-16 23:24

我有一个朋友给我的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 个回答

2

在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则满足时,程序才会做出反应。

比如说,如果你想让程序在用户输入的数字大于10时显示一条消息,你就需要用到“条件语句”。这就像在问:“如果这个数字大于10,那就告诉我。”

条件语句通常是用“如果……那么……”的结构来写的。这样,程序就能根据不同的输入做出不同的反应。

在编程中,理解这些基本的逻辑是非常重要的,因为它们帮助我们控制程序的行为,让程序变得更加智能。

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

你可以通过使用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语句定义了一个内联函数。在这个函数里,三元条件首先检查给定的路径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)

撰写回答