Как извлечь только имена файлов? - PullRequest
0 голосов
/ 27 марта 2019

У меня есть текстовый файл, и я хочу извлечь только полное имя файла.

Я использую ноутбук Jupyter с последней установленной версией Python. Я пытался использовать 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 голосов
/ 27 марта 2019

Следующий код сделает это за вас

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
...