📌  相关文章
📜  从文件路径获取文件名的Python程序

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

从文件路径获取文件名的Python程序

在本文中,我们将研究从Python编程语言中的给定文件路径获取文件名的程序。

有时在自动化过程中,我们可能需要从文件路径中提取的文件名。最好了解——

  • Python操作系统模块
  • Python路径模块
  • 常用表达

方法一:使用Python OS-module从文件路径中获取文件名

Python3
import os
 
file_path = 'C:/Users/test.txt'  # file path
 
# using basename function from os
# module to print file name
file_name = os.path.basename(file_path)
 
print(file_name)


Python3
import os
 
file_path = 'C:/Users/test.txt'
 
file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)
 
print(file)  # returns tuple of string
 
print(file[0] + file[1])


Python3
from pathlib import Path
 
file_path = 'C:/Users/test.txt'
 
# stem attribute extracts the file
# name
print(Path(file_path).stem)
 
# name attribute returns full name
# of the file
print(Path(file_path).name)


Python3
import re
 
file_path = 'C:/Users/test.txt'
pattern = '[\w-]+?(?=\.)'
 
# searching the patter
a = re.search(pattern, file_path)
 
# printing the match
print(a.group())


输出:

test.txt

这个方法最终会得到一个文件,它是一个扩展名,但是如果我们只需要没有扩展名的文件名或只需要扩展名怎么办。这里 os 模块中的splitext函数出现了。

Syntax - os.path.splittext(file_name) 

此方法将返回一个包含文件名和文本的字符串元组,我们可以在索引的帮助下访问它们。

例子:

Python3

import os
 
file_path = 'C:/Users/test.txt'
 
file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)
 
print(file)  # returns tuple of string
 
print(file[0] + file[1])

输出:

('test', '.txt')
test.txt

方法2:使用Pathlib从文件路径中获取文件名

Stem 属性可以从没有扩展名的链接中提取文件名,但是如果我们想要文件的扩展名,我们可以使用名称属性

例子:

Python3

from pathlib import Path
 
file_path = 'C:/Users/test.txt'
 
# stem attribute extracts the file
# name
print(Path(file_path).stem)
 
# name attribute returns full name
# of the file
print(Path(file_path).name)

输出:

test
test.txt

方法3:使用正则表达式从文件路径中获取文件名

我们可以使用正则表达式将文件名与特定模式匹配。学习正则表达式请参考这篇文章

Pattern - [\w]+?(?=\.)

该图案分为3个图案

  • [\w] 匹配集合内的单词
  • +?匹配字符串,如果它之前只出现一次?关键词
  • (?=) 匹配所有没有换行符的字符并确保停止。

例子:

Python3

import re
 
file_path = 'C:/Users/test.txt'
pattern = '[\w-]+?(?=\.)'
 
# searching the patter
a = re.search(pattern, file_path)
 
# printing the match
print(a.group())

输出:

test