Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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))

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])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top