How do I select part of a filename (leave out the extension) in Python? [duplicate]

StackOverflow https://stackoverflow.com/questions/22456971

  •  16-06-2023
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top