|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
Listing file names w/o the extensions
Greets,
I have a small program I use to keep track of some of my customers info.All customer info is written into a text file(each file named after the customer),and I have a option to list the files in the customers directory.I am currently using os.listdir() to display the files,but all the ".txt" extensions makes reading a long list a little hard on the eye.I could slice the extensions off,but I suspect there is a better way to do it. Can anyone recommend a way to list the files without showing the extensions? *edit* Sorry for this,but since I can't delete the thread,I guess I'll just post what I have done using slices,and fix spelling errors Code:
list=os.listdir('path/to/dir/')
for i in list:
print i[:-4]
This works just fine for me,and allowes me to display the file name w/o the extension
__________________
It is not important if the glass is half full or half empty.What is important,is who has been drinking from MY glass?!?!? |
|
#2
|
|||
|
|||
|
Hi there.
I had a similar problem in the past, and solved it using the exact same method as you. I believe that the functionality/method you're looking for doesn't actually exist. Why not send the guys over at python.org an e-mail requesting an extension of the glob module? The glob.glob('*') which is similar/identical to your os.listdir() method could be extended to return a list without file extensions by calling it with glob.glob('*', NO_EXTENSION) for example. Just a thought. Cheers, K ![]() |
|
#3
|
||||
|
||||
|
Just a thought - what if the directory does not just contain files with the right extension?
I think it would be safer to try this: Code:
>>> import glob
>>> textfiles = [x[:-4] for x in glob.glob("*.txt")]
>>> textfiles
['MOTD', 'LICENSE', 'README', 'NEWS', 'text', 'log1', 'log2', 'diff', 'Document1', 'Document2']
grim ![]()
__________________
*** Experimental Python Markup CGI V2 *** |
|
#4
|
|||
|
|||
|
What if some of the files have longer extensions?
Code:
>>> import os, sys
>>> os.path.extsep
'.'
>>> os.path.splitext("c:\\a.txt")
('c:\\a', '.txt')
>>> import glob
>>> f = glob.glob("e:\\*.txt")
>>> f[0]
'e:\\contacts.txt'
>>> os.path.basename(f[0])
'contacts.txt'
>>> [os.path.splitext(os.path.basename(x))[0] for x in glob("d:\\*.txt")
![]() |
|
#5
|
||||
|
||||
|
Yep, that was a more robust solution
![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Listing file names w/o the extentions |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|