简体   繁体   English

如何获取文件上游两个目录的文件夹路径名?

[英]How can I get the pathname of the folder two directories upstream of a file?

Using glob2 and os I would like the directory '/a/b/' given the file path '/a/b/c/xyz.txt' 使用glob2和os,我想要目录'/a/b/' ,文件路径为'/a/b/c/xyz.txt'

I have been able to (recursively) move forward through directories using /* and /** in glob2, but not backwards through parent directories. 我已经能够(递归)在glob2中使用/*/**在目录中前进,但不能在父目录中前进。 I don't want to use regular expressions or split. 我不想使用正则表达式或拆分。 Is there a simple way to do this using glob and/or os? 是否有使用glob和/或os的简单方法?

Why glob? 为什么是球?

dir_path = file_path.split('/')
what_i_want = '/' + dir_path[10] + '/' + dir_path[1] + '/'

You can also do this by finding the index of the 3rd slash, using the return of each call as the "start" argument to the next. 您也可以通过找到第三个斜杠的索引来实现此目的,并将每个调用的返回用作下一个的“开始”参数。

third_slash = file_path.index('/', file_path.index('/', file_path.index('/')+1) +1)
what_i_want = file_path[:third_slash+1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何递归地打印每个文件或文件夹的路径名 - how to print the pathname of every file or folder recursively 如果路径名包含单个反逗号并且出现错误,如何在 pandas 中读取 csv 文件? - How to read csv file in pandas if the pathname contains single inverted comma and i get error? 检索两个单独文件夹(目录)中的文件列表。 如何获取终端中打印的内容以打印到新的文本文档中? - List of files in two separate file folders (directories) is retrieved. How do I get what prints in the terminal to print into a new text document? 如何获得不同目录中的所有文件名? - How can I get all filename in different directories? 如何递归查找包含某种类型文件的*目录*? - How can I recursively find the *directories* containing a file of a certain type? 如何通过 python 中安装的谷歌驱动器上文件的路径获取文件/文件夹的共享链接? - How can I get share link of file/folder by path to the file on insalled google drive in python? 如何在 Python 中删除文件或文件夹? - How can I delete a file or folder in Python? 如何在 python 中获取路径以及文件夹中第一个文件的名称等 - how can i get the path plus the name of the first file in a folder and so on in python 如何通过单击 GUI 上的按钮将图像放入同一目录文件夹中的另一个 .py 文件中 - How can i get image by click button on GUI into another .py file in the same directory folder 如何获取文件夹中文件的创建时间戳? [蟒蛇] [csv] - How can I get the creation timestamp of a file which is in a folder ? [python] [csv]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM