如何仅提取文件名?

时间:2019-03-27 10:43:34

标签: python split jupyter-notebook

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

我正在使用安装了最新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

1 个答案:

答案 0 :(得分:0)

以下代码将为您完成

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