user2165857
user2165857

Reputation: 2710

Split file name by character

I would like to split a file name using a specific character within the file name. For instance:

FileName = MyFile_1.1_A.txt
(File, ext) = os.path.splitext(FileName)
print File

This will give an output of:

MyFile_1.1_A

However, I would like to get an output of:

MyFile_1.1

How can I do this?

Upvotes: 0

Views: 1814

Answers (4)

iruvar
iruvar

Reputation: 23394

Another variation

FileName.rpartition('_')[0]

Upvotes: 5

dawg
dawg

Reputation: 104102

>>> fn='MyFile_1.1_A.txt'
>>> re.split(r'_[^_]*$',fn)
['MyFile_1.1', '']
>>> fn='file_name_with_many_under_scores_1.1_.txt'
>>> re.split(r'_[^_]*$',fn)
['file_name_with_many_under_scores_1.1', '']

Upvotes: 1

Brian Cain
Brian Cain

Reputation: 14619

how about:

FileName = 'MyFile_1.1_A.txt'
File = '_'.join(FileName.rsplit('_')[:-1])
print File

For example, this also handles another case:

In [1]: FileName = 'MyFile_ohyeah_1.1_A.txt'

In [2]: File = '_'.join(FileName.rsplit('_')[:-1])

In [3]: File
Out[3]: 'MyFile_ohyeah_1.1'

Upvotes: 1

karthikr
karthikr

Reputation: 99680

If the file format is standard, you can use rsplit

print FileName.rsplit('_', 1)[0]

Upvotes: 5

Related Questions