删除部分路径

2024-04-28 22:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

/​share/​Downloads/​Videos/​Movies/​Big.Buck.Bunny.​720p.​Bluray.​x264-BLA.​torrent/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA

但是,我不想有“Big.Buck.Bunny.720p.Bluray.x264 BLA.torrent/”在其中,我希望路径如下:

/​share/​Downloads/​Videos/​Movies/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA

对于正则表达式,我基本上想计算所有包含*.torrent./的内容,如何在regexp中实现这一点?

谢谢!


Tags: 数据路径share内容downloadsmoviestorrentvideos
3条回答

无需使用regexp即可执行此操作:

>>> x = unicode('/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA')
>>> x.rfind('.torrent')
66
>>> x[:x.rfind('.torrent')]
u'/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA'

你甚至不需要正则表达式。您可以使用^{}^{}

os.path.join(os.path.dirname(os.path.dirname(path)),
             os.path.basename(path))

其中path是文件的原始路径。

或者,也可以按如下方式使用^{}

dirname, filename = os.path.split(path)
os.path.join(os.path.dirname(dirname), filename)

注意,这将在假设您要删除的是包含路径中文件的目录名的情况下工作,如问题中的示例所示。

I basically want to math anything that holds *.torrent./, how can I accomplish this in regexp?

您可以使用:

[^/]*\.torrent/

假设最后一个.是一个拼写错误。

相关问题 更多 >