简体   繁体   中英

Removing the end of a filename in python

I need to remove the end off a filename below:

Testfile_20190226114536.CSV.986466.1551204043175

So anything after CSV needs to be removed so i have a file named:

Testfile_20190226114536.CSV

假设file_name = "Testfile_20190226114536.CSV.986466.1551204043175"

file_name = file_name.split('.CSV')[0] + '.CSV'

As simple as this:

s = 'Testfile_20190226114536.CSV.986466.1551204043175'
suffix = '.CSV'

s[:s.rindex(suffix) + len(suffix)]
=> 'Testfile_20190226114536.CSV'

You can use re.sub :

import re
result = re.sub('(?<=\.CSV)[\w\W]+', '', 'Testfile_20190226114536.CSV.986466.1551204043175')

Output:

'Testfile_20190226114536.CSV'

The easy way is this

All of your files have this "CSV" in the middle?

You can try split and join your name like this:

name = "Testfile_20190226114536.CSV.986466.1551204043175"
print ".".join(name.split(".")[0:2])

Here's the steps to see what's going on

>>> filename = 'Testfile_20190226114536.CSV.986466.1551204043175'

# split the string into a list at '.'
>>> l = filename.split('.')

>>> print(l)
['Testfile_20190226114536', 'CSV', '986466', '1551204043175']

# index the list to get all the elements before and including 'CSV'
>>> filtered_list = l[0:l.index('CSV')+1]

>>> print(filtered_list)
['Testfile_20190226114536', 'CSV']

# join together the elements of the list with '.'
>>> out_string = '.'.join(filtered_list)
>>> print(out_string)

Testfile_20190226114536.CSV

Here's a full function:

def filter_filename(filename):
    l = filename.split('.')
    filtered_list = l[0:l.index('CSV')+1]
    out_string = '.'.join(filtered_list)
    return out_string

>>> filter_filename('Testfile_20190226114536.CSV.986466.1551204043175')
'Testfile_20190226114536.CSV'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM