如何只提取文件名?

2024-06-16 13:35:50 发布

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

我有一个文本文件,我只想提取完整的文件名

我正在使用安装了最新python的jupyter笔记本。我试过使用split()方法,但这不是我想要的。这是我的密码:

with open(r'C:\Users\Shaunvinder Singh\Desktop\OneDrive_2019-03-26\timelines\ministries\replies\list.txt') as my_file:
    for line in my_file:
        str = line.split(' - {',)
        print(str)

C:\\Users\\Shaunvinder Singh\\Desktop\\OneDrive_2019-03-26\\timelines\\ministries\\replies\\KATSMalaysia\\KATSMalaysia2019-02-04.csv

Tags: 文件名mylineonedriveusersfilesplit文本文件
1条回答
网友
1楼 · 发布于 2024-06-16 13:35:50

下面的代码可以为你做

import os
print(os.path.basename(your_path))

import os

file_path = "C:\\Users\\Shaunvinder Singh\\Desktop\\OneDrive_2019-03-26\\timelines\\ministries\\replies\\KATSMalaysia\\KATSMalaysia2019-02-04.csv"

'''
Return a normalized absolutized version of the pathname path. 
On most platforms, this is equivalent to calling the function 
normpath() as follows: normpath(join(os.getcwd(), path)).
'''
print(os.path.abspath(file_path))

'''
Return the base name of pathname path. This is the second 
element of the pair returned by passing path to the function 
split(). Note that the result of this function is different 
from the Unix basename program; where basename for '/foo/bar/' 
returns 'bar', the basename() function returns an empty string ('')
'''
print(os.path.basename(file_path))

'''
Return the directory name of pathname path. 
This is the first element of the pair returned 
by passing path to the function split().
'''
print(os.path.dirname(file_path))

'''
Return the canonical path of the specified filename, eliminating 
any symbolic links encountered in the path (if they are supported 
by the operating system)

'''
print(os.path.realpath(file_path))

'''
Split the pathname path into a pair (root, ext) such that root 
+ ext == path, and ext is empty or begins with a period and 
contains at most one period. Leading periods on the basename 
are ignored; splitext('.cshrc') returns ('.cshrc', '').
'''
print(os.path.splitext(file_path))

参考文献:

https://docs.python.org

相关问题 更多 >