简体   繁体   中英

Python3 Windows 7 file path handling

I have fetched files from windows shared drive having path as follows:

\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls

I want to fetch filename from this path which is futurefilesomf.egus.xls

when I tried as file_path.split('\\') . It's giving error as SyntaxError: EOL while scanning string literal

I can't do file_path.split('\\\\') because then it will give me None .

Even if I do file_path.replace('\\\\','\\') , still same error.

What could be the solution.

You can do file_path.split('\\\\') . Do it like this:

>>> file_path=r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
>>> file_path.split('\\')
['', '', 'piyush123', 'piyushtech$', 'Piyush', 'ProFileTesting', 'May', 'Input_File', 'OMF', 'futurefilesomf.egus.xls']

Though you problably really need to combine it with a function from the os.path family, for example:

>>> os.path.splitunc(file_path)
('\\\\piyush123\\piyushtech$', '\\Piyush\\ProFileTesting\\May\\Input_File\\OMF\\futurefilesomf.egus.xls')

Use basename instead of splitting:

>>> s = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
>>> import os
>>> os.path.basename(s)
'futurefilesomf.egus.xls'

You can use ntpath:

full_path = r'\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls'

import ntpath

ntpath.split(full_path)

which gives:

('\\\\piyush123\\piyushtech$\\Piyush\\ProFileTesting\\May\\Input_File\\OMF', 'futurefilesomf.egus.xls')

Marked as 3.x so I'll assume you have 3.4+ available for Pathlib

import pathlib

path = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
print(pathlib.Path(path).name)
print(pathlib.Path(path).name == "futurefilesomf.egus.xls")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM