【问题标题】:How to remove specific directory names from path list如何从路径列表中删除特定目录名称
【发布时间】:2013-08-07 20:50:30
【问题描述】:

我有一个包含媒体文件的 zip 文件,在我提取这些文件并将路径附加到我的数据库之前,我需要清理路径,并提取 zip。

来自 zip 的路径列表包含

/no-fixed-name/no-fixed-name/images/2012/03/image.jpg
/no-fixed-name/no-fixed-name/images/2012/03/any-image.jpg
/no-fixed-name/no-fixed-name/videos/2012/03/video.mp4

我想去掉第一个两个目录的路径并得到这个

/images/2012/03/image.jpg
/images/2012/03/any-image.jpg

并将"http://my-cdn-path.com/" 加入每个路径

到目前为止,我已经这样做了,但无法将其剥离。

import os
import zipfile
import fnmatch

zf = zipfile.ZipFile('samplezip.zip','r')

a = zf.namelist()
search = '*.png'
searchresult = fnmatch.filter(a, search)


for i in searchresult:
   yo = os.path.abspath(i).split(os.sep)[2]
   #This way I can get the dir name that I want to remove but not sure how to do that.

【问题讨论】:

    标签: python django path


    【解决方案1】:

    您可以执行以下操作(将路径视为字符串):

    'http://my-cdn-path.com/' + '/'.join(i.split('/')[-4:]))
    

    或者,使用 os.path:

    'http://my-cdn-path.com/' + '/'.join(os.path.abspath(i).split(os.sep)[-4:])
    

    【讨论】:

    • 请注意,join 不会在字符串的开头添加斜杠,因此基本 URL 应该以斜杠结尾。
    • 进行了此更改。谢谢!
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多