📌  相关文章
📜  使用Python从没有扩展名的路径中获取文件名

📅  最后修改于: 2022-05-13 01:55:50.884000             🧑  作者: Mango

使用Python从没有扩展名的路径中获取文件名

使用路径从Python获取文件名是一个复杂的过程,不是因为我们需要使用正则表达式将文件名与路径分开,而是因为不同操作系统中的文件路径中使用了不同类型的分隔符。例如,Linux 或 Mac Os 等基于 UNIX 的系统使用“/”(正斜杠)作为目录的分隔符,而 Windows 使用“\”(反斜杠)分隔路径内的目录。因此,为了避免所有这些问题,我们将在Python ntpath 中使用一个内置包,并使用它首先提取基本名称(包含带有扩展名的文件名的名称)。然后我们可以使用简单的Python切片来查找没有扩展名的文件名。

循序渐进的方法:

  • 首先,我们将使用ntpath模块。其次,我们将从路径中提取文件的基本名称并将其附加到一个单独的数组中。相同的代码是这样的。
Python3
# import module
import ntpath
  
# used path style of both the UNIX
# and Windows os to show it works on both.
paths = [
    "E:\Programming Source Codes\Python\sample.py",
    "D:\home\Riot Games\VALORANT\live\VALORANT.exe"]
  
# empty array to store file basenames
filenames = []
  
for path in paths:
    # used basename method to get the filename
    filenames.append(ntpath.basename(path))


Python3
# get names from the list
for name in filenames:
    
    # finding the index where 
    # the last "." occurs
    k = name.rfind(".")
      
    # printing the filename
    print(name[:k])


Python3
# import module
import ntpath
  
# used path style of both the UNIX
# and Windows os to show it works on both.
paths = [
    "E:\Programming Source Codes\Python\sample.py",
    "D:\home\Riot Games\VALORANT\live\VALORANT.exe"]
  
# empty array to store file basenames
filenames = []
  
for path in paths:
    
    # used basename method to get the filename
    filenames.append(ntpath.basename(path))
  
# get names from the list
for name in filenames:
    
    # finding the index where 
    # the last "." occurs
    k = name.rfind(".")
      
    # printing the filename
    print(name[:k])


  • 然后我们将使用生成的数组并找到最后一次出现的“.”。字符中的字符串。记住只找到“.”的实例。如果文件名本身包含“.”,而不是最后一次出现可能会产生问题。我们将使用rfind找到该索引,然后最后对索引之前的字符串部分进行切片以获取文件名。代码看起来像这样。同样,您可以将这些文件名存储在列表中并在其他地方使用它们,但在这里我们决定简单地将它们打印到屏幕上。

蟒蛇3

# get names from the list
for name in filenames:
    
    # finding the index where 
    # the last "." occurs
    k = name.rfind(".")
      
    # printing the filename
    print(name[:k])

下面是完整的程序:

蟒蛇3



# import module
import ntpath
  
# used path style of both the UNIX
# and Windows os to show it works on both.
paths = [
    "E:\Programming Source Codes\Python\sample.py",
    "D:\home\Riot Games\VALORANT\live\VALORANT.exe"]
  
# empty array to store file basenames
filenames = []
  
for path in paths:
    
    # used basename method to get the filename
    filenames.append(ntpath.basename(path))
  
# get names from the list
for name in filenames:
    
    # finding the index where 
    # the last "." occurs
    k = name.rfind(".")
      
    # printing the filename
    print(name[:k])

输出: