简体   繁体   English

将文件名与路径分开

[英]Separate file name from path

I have a file whose path is like this : D:\\Documents and Settings\\user\\Desktop\\Folder\\File1.txt. 我有一个路径如下的文件:D:\\ Documents and Settings \\ user \\ Desktop \\ Folder \\ File1.txt。 Here File1.txt is file name. 这里File1.txt是文件名。 Now I want to separate this file name from the file path. 现在,我想将此文件名与文件路径分开。 If I have, 如果我有,

path = C:\\Documents and Settings\\user\\Desktop\\Folder\\File1.txt 路径= C:\\ Documents and Settings \\ user \\ Desktop \\ Folder \\ File1.txt

then I want to store this name of the file in to filename . 然后我要将文件的这个名称存储到filename中 so output will look like this : filename=File1.txt I am not getting any idea about this. 所以输出看起来像这样: filename = File1.txt我对此一无所知。 I am new in python..can anybody help me please in python...??? 我是python的新手..有人可以在python中帮助我吗????

use os module 使用os模块

import os 
fileName = os.path.basename(path)

If you have already have pathname, just split it and extract the filename from it 如果您已经有路径名,只需将其拆分并从中提取文件名

path = "C:\\Documents and Settings\\user\\Desktop\\Folder\\File1.txt"
temp=path.split('\\')
filename=temp[-1]
print filename

If you want file name without knowing what os is , 如果您想要文件名而不知道os是什么,

try this , 尝试这个 ,

>>> import ntpath
>>> ntpath.basename("C:\Documents and Settings\user\Desktop\Folder\File1.txt")
'File1.txt'
>>> ntpath.basename("/etc/apache-perl/httpd.conf")
'httpd.conf'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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