如何在 Python 中访问父目录

发布于 2024-11-29 06:34:41 字数 2293 浏览 2 评论 0原文

我有一个朋友给我的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 中访问父目录的最佳方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青柠芒果 2024-12-06 06:34:41
import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PARENT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))
import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PARENT_DIR = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))
明媚殇 2024-12-06 06:34:41

您可以使用 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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文