473,725 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving Filename from Path

Hi,

Given a string representing the path to a file, what is the best way to
get at the filename? Does the OS module provide a function to parse the
path? or is it acceptable to split the string using '/' as delimiters
and get the last 'word'. The reason I'm not entirely happy with that
method is that it is platform specific. I would prefer to use a built
in method if possible.

Cheers,

Rob Cowie

Aug 31 '05 #1
2 23382
>>> import os.path
help(os.path)
Help on module ntpath:

NAME
ntpath - Common pathname manipulations, WindowsNT/95 version.

FILE
c:\data\utils\p ython24\lib\ntp ath.py

DESCRIPTION
Instead of importing this module directly, import os and refer to
this
module as os.path.

FUNCTIONS
abspath(path)
Return the absolute version of a path

basename(p)
Returns the final component of a pathname

commonprefix(m)
Given a list of pathnames, returns the longest common leading
component

dirname(p)
Returns the directory component of a pathname

exists(path)
Test whether a path exists

expanduser(path )
Expand ~ and ~user constructs.

If user or $HOME is unknown, do nothing.

expandvars(path )
Expand shell variables of form $var and ${var}.

Unknown variables are left unchanged.

getatime(filena me)
Return the last access time of a file, reported by os.stat()

getctime(filena me)
Return the creation time of a file, reported by os.stat().

getmtime(filena me)
Return the last modification time of a file, reported by
os.stat()

getsize(filenam e)
Return the size of a file, reported by os.stat()

isabs(s)
Test whether a path is absolute

isdir(path)
Test whether a path is a directory

isfile(path)
Test whether a path is a regular file

islink(path)
Test for symbolic link. On WindowsNT/95 always returns false

ismount(path)
Test whether a path is a mount point (defined as root of drive)

join(a, *p)
Join two or more pathname components, inserting "\" as needed

normcase(s)
Normalize case of pathname.

Makes all characters lowercase and all slashes into
backslashes.

normpath(path)
Normalize path, eliminating double slashes, etc.

realpath = abspath(path)
Return the absolute version of a path

split(p)
Split a pathname.

Return tuple (head, tail) where tail is everything after the
final slash.
Either part may be empty.

splitdrive(p)
Split a pathname into drive and path specifiers. Returns a
2-tuple
"(drive,pat h)"; either part may be empty

splitext(p)
Split the extension from a pathname.

Extension is everything from the last dot to the end.
Return (root, ext), either part may be empty.

splitunc(p)
Split a pathname into UNC mount point and relative path
specifiers.

Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.

walk(top, func, arg)
Directory tree walk with callback function.

For each directory in the directory tree rooted at top
(including top
itself, but excluding '.' and '..'), call func(arg, dirname,
fnames).
dirname is the name of the directory, and fnames a list of the
names of
the files and subdirectories in dirname (excluding '.' and
'..'). func
may modify the fnames list in-place (e.g. via del or slice
assignment),
and walk will only recurse into the subdirectories whose names
remain in
fnames; this can be used to implement a filter, or to impose a
specific
order of visiting. No semantics are defined for, or required
of, arg,
beyond that arg is always passed to func. It can be used,
e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common.

DATA
__all__ = ['normcase', 'isabs', 'join', 'splitdrive', 'split',
'splite...
altsep = '/'
curdir = '.'
defpath = r'.;C:\bin'
devnull = 'nul'
extsep = '.'
pardir = '..'
pathsep = ';'
sep = r'\'
supports_unicod e_filenames = True


Rob Cowie wrote: Hi,

Given a string representing the path to a file, what is the best way to
get at the filename? Does the OS module provide a function to parse the
path? or is it acceptable to split the string using '/' as delimiters
and get the last 'word'. The reason I'm not entirely happy with that
method is that it is platform specific. I would prefer to use a built
in method if possible.

Cheers,

Rob Cowie


Aug 31 '05 #2
Thanks,

os.path.basenam e(filePath) it is then.

BTW, the help(module) function is new to me! Must have missed it when
reading the tutorial.

Cheers!

Aug 31 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
5404
by: Don | last post by:
How do I retrieve the full path (C:\.....filename) of a file uploaded to a php script on the server. I think $_FILES will only provide 'name', which is only the filename itself. Thanks, Don ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =---
2
1864
by: VM | last post by:
How can I retrieve the whole directory where my exe is located? I would've thought Directory.GetCurrentDirectory worked but any event that may change the dir (eg. OpenFileDialog or SaveFileDialog) will change the current directory. Thanks.
2
50357
by: Csharper95 | last post by:
I want to get the file name and path from a SaveFileDialog (for a 'save as' operation) after the user has saved the information under a new file name (and presumably under a new path) ? I want to display the new file name and path in the Form.text Title. So how do I go about getting the info ? Heres my code:
7
1923
by: Dean McCarten | last post by:
I Need to Retrieve the UNC Path of Mapped Drives on a Client Machine's (NT4 + y2k) on my Network, but I have been unsuccessful so far and I find seem to find a way to do this, any idea anyone I need to try and finish this toda Thanks in Advanc Dean McCarte ASP/VBS/VB.NET & ASP.NET Develope Cumbria U
1
1455
by: Jon Pope | last post by:
I've got a web service which can be installed by a customer within a virtual folder whose name is defined by them during installation. For example, the path to the web service could be: http://<servername>/Service1/GetData.asmx http://<servername2>/MyService/Subfolder1/SubFolder2/GetData.asmx .... and so on.
1
3293
by: psbasha | last post by:
Hi, I would like to get the path of the given file name. Say I/P: C:\Sample\Sample1.txt
6
23134
by: SpreadTooThin | last post by:
After I select a file with the OpenFileDialog, I get the file name with .FileName, but I want to know the drive and path where that file is. What function, method, class can I use in C# to get the drive and path?
2
1475
by: =?Utf-8?B?SmFtZXM=?= | last post by:
Hi, I am aware of 256 characters path limit in naming a file, but can you help me how to limit the path for file naming to 240 characters only? is there a way to limit that in registry editor or is there a way to group policy (if so, pls. show me), we are using windows xp pro as our client pc and windows server 2003 std edtn R2 as our server. your help is very much appreciated Thanks, James
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.