0

I have a file whose path is like this : D:\Documents and Settings\user\Desktop\Folder\File1.txt. Here File1.txt is file name. 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

then I want to store this name of the file in to filename. so output will look like this : filename=File1.txt I am not getting any idea about this. I am new in python..can anybody help me please in python...???

Ruchir
  • 1,086
  • 4
  • 24
  • 48
  • do you have any code at all? what have you tried? – birthofearth Apr 23 '14 at 05:58
  • I am working on client-server networking in python. I have to send this file name to server. for this I've to separate this file name.so I've wrote complete code for client and server in python. – Ruchir Apr 23 '14 at 06:02
  • possible duplicate of [Python, extract file name from path, no matter what the os/path format](http://stackoverflow.com/questions/8384737/python-extract-file-name-from-path-no-matter-what-the-os-path-format) – Vincent Savard Apr 23 '14 at 06:04

3 Answers3

8

use os module

import os 
fileName = os.path.basename(path)
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
Abhishek Bansal
  • 5,197
  • 4
  • 40
  • 69
1

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
Jry9972
  • 463
  • 7
  • 16
0

If you want file name without knowing what os is ,

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'
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81