By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,872 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

Getting a extension of a given filename

100+
P: 440
Hi,

I need to extract the filename extension from the given filename at a particular location

I/P:
say 'C:\Sample\Sample1.txt'

O/P :
The file etension is '.txt'

Thanks
PSB
May 15 '07 #1
Share this Question
Share on Google+
9 Replies


Motoma
Expert 2.5K+
P: 3,235
Expand|Select|Wrap|Line Numbers
  1. def findExt(filename):
  2.    return filename.rpartition(".")[2]
  3.  
May 15 '07 #2

100+
P: 440
Expand|Select|Wrap|Line Numbers
  1. def findExt(filename):
  2.    return filename.rpartition(".")[2]
  3.  
Is it a filepointer or a Filename path?
May 15 '07 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Expand|Select|Wrap|Line Numbers
  1. >>> import os
  2. >>> p = r'C:\SDS2_7.0\macro\Zip\tem_v1.00.txt'
  3. >>> os.path.splitext(p)
  4. ('C:\\SDS2_7.0\\macro\\Zip\\tem_v1.00', '.txt')
  5. >>> 
May 15 '07 #4

Motoma
Expert 2.5K+
P: 3,235
Is it a filepointer or a Filename path?
The filename variable is a string.
May 15 '07 #5

Expert 100+
P: 511
Is it a filepointer or a Filename path?
you should also note that rpartition is available in Python 2.5. if earlier, use bv's method, or use the usual split way:
Expand|Select|Wrap|Line Numbers
  1. "c:\\test.txt.txt".split(".")[-1]
  2.  
May 16 '07 #6

Motoma
Expert 2.5K+
P: 3,235
Expand|Select|Wrap|Line Numbers
  1. >>> import os
  2. >>> p = r'C:\SDS2_7.0\macro\Zip\tem_v1.00.txt'
  3. >>> os.path.splitext(p)
  4. ('C:\\SDS2_7.0\\macro\\Zip\\tem_v1.00', '.txt')
  5. >>> 
Thanks bvdet. This would be the preferable way of doing it, in my opinion, as it is built into the language.
May 16 '07 #7

Expert 100+
P: 511
Thanks bvdet. This would be the preferable way of doing it, in my opinion, as it is built into the langage.
hmm..I cannot say if its "built in" (as in really built in , like str(), int) because to use os.path.splitext, we need to import os. but to use rpartition, as its a string method, just need "path".rpartition("") , much like split() method :)
May 16 '07 #8

Motoma
Expert 2.5K+
P: 3,235
hmm..I cannot say if its "built in" (as in really built in , like str(), int) because to use os.path.splitext, we need to import os. but to use rpartition, as its a string method, just need "path".rpartition("") , much like split() method :)
I agree with what you are saying; I guess what I was getting at is that the os.path.splitext was designed specifically for this purpose, whilst rpartition has a variety of uses.
May 16 '07 #9

P: 2
Check out this Python Articles
May 17 '07 #10

Post your reply

Sign in to post your reply or Sign up for a free account.