Python - 从长路径获取文件名

时间:2022-09-01 22:17:22

I have long paths to files like:

我有很长的路径文件,如:

D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv

What is the best way to get just the file name from there, so I end up with:

从那里获取文件名的最佳方法是什么,所以我最终得到:

Alexis Jordan - Good Girl

From there I want to cut the Artist and Title into separate parts, but I can manage that :)

从那里我想把艺术家和标题分成不同的部分,但我可以管理:)

2 个解决方案

#1


6  

First you need to decode the URL encoding with urllib.unquote() then use the os.path module to split out the filename and extension:

首先,您需要使用urllib.unquote()解码URL编码,然后使用os.path模块拆分文件名和扩展名:

import os
import urllib

path = urllib.unquote(path)
filename = os.path.splitext(os.path.basename(path))[0]

where os.path.basename() removes the directory path, and os.path.splitext() gives you a filename and extension tuple.

os.path.basename()删除目录路径,os.path.splitext()为您提供文件名和扩展名元组。

This then gives you the filename:

然后,它会为您提供文件名:

>>> import os
>>> import urllib
>>> path = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
>>> path = urllib.unquote(path)
>>> path
'D:\\Media\\Music Videos\\Alexis Jordan - Good Girl.mkv'
>>> filename = os.path.splitext(os.path.basename(path))[0]
>>> filename
'Alexis Jordan - Good Girl'

#2


2  

from urllib2 import unquote
from os.path import basename

p = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
fname = basename(unquote(p))

#1


6  

First you need to decode the URL encoding with urllib.unquote() then use the os.path module to split out the filename and extension:

首先,您需要使用urllib.unquote()解码URL编码,然后使用os.path模块拆分文件名和扩展名:

import os
import urllib

path = urllib.unquote(path)
filename = os.path.splitext(os.path.basename(path))[0]

where os.path.basename() removes the directory path, and os.path.splitext() gives you a filename and extension tuple.

os.path.basename()删除目录路径,os.path.splitext()为您提供文件名和扩展名元组。

This then gives you the filename:

然后,它会为您提供文件名:

>>> import os
>>> import urllib
>>> path = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
>>> path = urllib.unquote(path)
>>> path
'D:\\Media\\Music Videos\\Alexis Jordan - Good Girl.mkv'
>>> filename = os.path.splitext(os.path.basename(path))[0]
>>> filename
'Alexis Jordan - Good Girl'

#2


2  

from urllib2 import unquote
from os.path import basename

p = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
fname = basename(unquote(p))