Reputation: 2710
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
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
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