473,729 Members | 2,344 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to get the extension of a filename from the path

Lad
Hello,
what is a way to get the the extension of a filename from the path?
E.g., on my XP windows the path can be
C:\Pictures\MyD ocs\test.txt
and I would like to get
the the extension of the filename, that is here
txt
I would like that to work on Linux also
Thank you for help
L.

Dec 8 '05 #1
8 8558
Lad wrote:
Hello,
what is a way to get the the extension of a filename from the path?
E.g., on my XP windows the path can be
C:\Pictures\MyD ocs\test.txt
and I would like to get
the the extension of the filename, that is here
txt
I would like that to work on Linux also
Thank you for help
L.


Like this, you mean?
import os.path
os.path.splitex t("c:\\pictures \\mydocs\\test. txt")

('c:\\pictures\ \mydocs\\test', '.txt')

--
Dale Strickland-Clark
Riverhall Systems www.riverhall.co.uk
Dec 8 '05 #2
On Thu, 8 Dec 2005, Lad wrote:
what is a way to get the the extension of a filename from the path?
E.g., on my XP windows the path can be
C:\Pictures\MyD ocs\test.txt
and I would like to get
the the extension of the filename, that is here
txt
You want os.path.splitex t:
import os
os.path.splitex t("C:\Pictures\ MyDocs\test.txt ") ('C:\\Pictures\ \MyDocs\test', '.txt') os.path.splitex t("C:\Pictures\ MyDocs\test.txt ")[1] '.txt'

I would like that to work on Linux also


It'll be fine.

tom

--
[Philosophy] is kind of like being driven behind the sofa by Dr Who -
scary, but still entertaining. -- Itchyfidget
Dec 8 '05 #3
"Lad" <py****@hope.cz > wrote:
what is a way to get the the extension of a filename from the path?
E.g., on my XP windows the path can be
C:\Pictures\MyD ocs\test.txt
and I would like to get
the the extension of the filename, that is here
txt

I would like that to work on Linux also
Thank you for help


os.path.splitex t(filename) splits a filename into a name part (which may include
a path) and an extension part:

import os
f, e = os.path.splitex t(filename)

the extension will include the separator, so the following is always true:

assert f + e == filename

if you don't want the period, you can strip it off:

if e[:1] == ".":
e = e[1:]

but it's often easier to change your code to take the dot into account; instead
of

if e[:1] == ".":
e = e[1:]
if e == "txt":
handle_text_fil e(filename)
elif e in ("png", "jpg"):
handle_image_fi le(filename)

do

if e == ".txt":
handle_text_fil e(filename)
elif e in (".png", ".jpg"):
handle_image_fi le(filename)

on the other hand, for maximum portability, you can use

f, e = os.path.splitex t(filename)
if e.startswith(os .extsep):
e = e[len(os.extsep):]
if e == "txt":
...

but that's probably overkill...

</F>

Dec 8 '05 #4

Lad wrote:
Hello,
what is a way to get the the extension of a filename from the path?
E.g., on my XP windows the path can be
C:\Pictures\MyD ocs\test.txt
and I would like to get
the the extension of the filename, that is here
txt
I would like that to work on Linux also
Thank you for help
L.


minor footnote: windows paths can be raw strings for os.path.split() ,
or you can escape "/"
tho Tom's examp indicates unescaped, non-raw string works with
splitext()

import os.path
# winpath='C:\\Pi ctures\\MyDocs\ \test.txt'
winpath=r'C:\Pi ctures\MyDocs\t est.txt'
fpath,fname_ext =os.path.split( winpath)
print "path: %s ;;;;; fname and ext: %s"%(fpath, fname_ext)
ext=fname_ext.s plit(".")[-1]
print ext

Dec 8 '05 #5
Fredrik Lundh wrote:
on the other hand, for maximum portability, you can use

f, e = os.path.splitex t(filename)
if e.startswith(os .extsep):
e = e[len(os.extsep):]
if e == "txt":
...


Is there ever a time when the original `e` could evaluate True, yet not
startswith(os.e xtsep)? In other words, could the first test be just

if e:
e = e[len(os.extsep):]

Also, note that for truly maximum portability one probably needs to add
to the code some knowledge of case-sensitivity and do a .lower() when
appropriate, as "txt" and "TXT" (and others) are equivalent on Windows
file systems. On that note, is there a common idiom for detecting that
information?

-Peter

Dec 8 '05 #6
Lad
Thank you ALL for help
Regards,
L.

Dec 8 '05 #7

Lad wrote:
Thank you ALL for help
Regards,
L.


addendum: ASPN Python cookbook often has something relevant /
modifiable for your needs:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/81931
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52661

(in this case code from 2001 / 2 is probably py 2.0 or 2.1, shd still
work)

Dec 8 '05 #8
On Thu, 8 Dec 2005, gene tani wrote:
Lad wrote:
what is a way to get the the extension of a filename from the path?


minor footnote: windows paths can be raw strings for os.path.split() ,
or you can escape "/"
tho Tom's examp indicates unescaped, non-raw string works with
splitext()


DOH. Yes, my path's got a tab in it, hasn't it!

tom

--
Women are monsters, men are clueless, everyone fights and no-one ever
wins. -- cleanskies
Dec 9 '05 #9

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

Similar topics

12
7966
by: hokiegal99 | last post by:
The below code does what I need it to do, but I thought that using something like ext = os.path.splitext(fname) and then searching ext for '.mp3' would be a much more accurate approach to solving this problem. Could someone demonstrate how to search ext for a specific string? This script works great for deleting illegal music on user machines ;) Thanks!!!
0
1922
by: travis ray | last post by:
Hi, I have an extension in which a file object is created in python and passed down to a c extension which attempts to read from it or write to it. Writing to the file pointer seems to work okay, but reading from it results in EBADF. It also causes python to crash on exit. I've attached the minimal (I think) c code, python code, build script, build log, and run log. Any and all help is greatly appreciated.
2
2428
by: Vilmar Brazão de Oliveira | last post by:
Hi, How verify type or extension of file using ASPUPLOAD? I check documentation, but I didn't find anything else yet. thanks, -- ««««««««»»»»»»»»»»»»»» Vlmar Brazão de Oliveira Desenvolvimento Web
4
4726
by: Peter A. Schott | last post by:
Trying to operate on a list of files similar to this: test.1 test.2 test.3 test.4 test.10 test.15 test.20
18
7716
by: Keith Brown | last post by:
I have an application that allows embedded storage of ANY chosen file in an OLE field. The file could have been dragged-and-dropped into the field or it might have been selected and imported programmatically using the common file dialog. Regardless, I need to determine the filetype/extension of each of these files already stored in my OLE fields and display it for the user. Double-clicking the raw OLE field or using the .Verb =...
1
4044
by: Adam Nowotny | last post by:
We use this code to open files such as doc, pdf and html in it's associated applications, "FileName" is something like "C:\......\foo.pdf" or "C:\.......\foo.doc". objProcess = New System.Diagnostics.Process objProcess.StartInfo.FileName = FileName objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal objProcess.StartInfo.UseShellExecute = True objProcess.Start()
0
1949
by: robert | last post by:
e.g. open/os module functions (os.path.getmtime...) and win32api/win32file functions fail on long paths (>~255 chars) even the '\\?\' trick from http://www.google.com/url?sa=D&q=http://msdn.microsoft.com/library/default.asp%3Furl%3D/library/en-us/fileio/fs/naming_a_file.asp does not work: >>> os.path.getmtime('\\\\?\\'+fabs) Traceback (most recent call last): File "<interactive input>", line 1, in ?
3
9115
by: Phoe6 | last post by:
Hi all, I had a filesystem crash and when I retrieved the data back the files had random names without extension. I decided to write a script to determine the file extension and create a newfile with extension. --- method 1: # File extension utility. import os
8
7469
by: Ron | last post by:
I am building a dynamic image loading class. I have a list of properties that have associated images in a specified directory. The problem they are multiple formats which are not known at runtime...and to make matters worse users are allowed to use images in any format...so long as they have the filename that matches the property name. My problem stems from the fact that I dont know the extension of the file...only the filename...so...
0
9281
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
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
9142
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...
1
6722
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
6022
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
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.