For example if I have the variable "file.txt", I want to be able to save only "file" to a variable. What I'd like is to eliminate whatever is beyond the last dot (including the dot). So if i had "file.version2.txt", I'd be left with "file.version2". Is there a way to do this?
Asked
Active
Viewed 1,821 times
1
-
check this out [remove last n charecters][1] [1]: http://stackoverflow.com/questions/10645959/how-do-i-remove-the-last-n-characters-from-a-string – kaushik94 Mar 17 '14 at 14:30
-
using a combination of `os.path.basename` and `os.path.splitext` seems a good start – El Bert Mar 17 '14 at 14:36
3 Answers
7
you have to use os.path.splitext
In [3]: os.path.splitext('test.test.txt')
Out[3]: ('test.test', '.txt')
In [4]: os.path.splitext('test.test.txt')[0]
Out[4]: 'test.test'
full reference for similar manipulations can be found here http://docs.python.org/2/library/os.path.html
-
1This is exactly what I needed. All i needed to add was "import os" before using os.path.splitext – Stefan Urziceanu Mar 17 '14 at 14:36
-
-
1it tells me I have to wait a few minutes, otherwise I would have :) – Stefan Urziceanu Mar 17 '14 at 14:41
-
1
If this is not too long you can do something like this if the file is in same directory
old_f = 'file.version2.txt'
new_f = old_f.split('.')
sep = '.'
sep.join(new_f[:-1]) # or assign it to a variable current_f = sep.join(new_f[:-1])

Gatsby Great
- 45
- 7