473,583 Members | 3,460 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 8549
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
7950
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...
0
1890
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...
2
2423
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
4717
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
7702
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...
1
4037
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...
0
1941
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...
3
9104
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
7455
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...
0
7893
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...
0
7821
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...
0
8172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8317
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...
1
7928
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...
0
6574
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...
0
5369
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...
1
2326
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
0
1151
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...

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.