[英]Python3 Windows 7 file path handling
我已经从Windows共享驱动器中获取文件,其路径如下:
\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls
我想从此路径中获取文件名,即futurefilesomf.egus.xls
当我尝试作为file_path.split('\\')
。 SyntaxError: EOL while scanning string literal
,错误为SyntaxError: EOL while scanning string literal
我不能做file_path.split('\\\\')
因为那样会给我None
。
即使我执行file_path.replace('\\\\','\\')
,仍然是相同的错误。
有什么解决方案。
您可以执行file_path.split('\\\\')
。 像这样做:
>>> 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']
尽管您可能确实需要将其与os.path
家族的功能结合起来,例如:
>>> os.path.splitunc(file_path)
('\\\\piyush123\\piyushtech$', '\\Piyush\\ProFileTesting\\May\\Input_File\\OMF\\futurefilesomf.egus.xls')
使用basename
而不是拆分:
>>> s = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
>>> import os
>>> os.path.basename(s)
'futurefilesomf.egus.xls'
您可以使用ntpath:
full_path = r'\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls'
import ntpath
ntpath.split(full_path)
这使:
('\\\\piyush123\\piyushtech$\\Piyush\\ProFileTesting\\May\\Input_File\\OMF', 'futurefilesomf.egus.xls')
标记为3.x,所以我假设您有3.4+可用于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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.