1

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?

Stefan Urziceanu
  • 237
  • 1
  • 3
  • 10
  • 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 Answers3

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

NiRR
  • 4,782
  • 5
  • 32
  • 60
Nilesh
  • 20,521
  • 16
  • 92
  • 148
2

Using the module os.path you can retrieve the full name of the file and then remove the extension:

import os
file_name, file_ext = os.path.splitext(os.path.basename(path_to_your_file))
El Bert
  • 2,958
  • 1
  • 28
  • 36
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])