首页 > 解决方案 > 如何仅提取文件名?

问题描述

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

我正在使用安装了最新 python 的 jupyter notebook。我尝试过使用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

标签: pythonsplitjupyter-notebook

解决方案


下面的代码会为你做

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

推荐阅读