我需要从以下文件名中删除结尾:
superview
所以CSV之后的所有内容都需要删除,所以我有一个名为:
Testfile_20190226114536.CSV.986466.1551204043175
答案 0 :(得分:1)
假设file_name = "Testfile_20190226114536.CSV.986466.1551204043175"
file_name = file_name.split('.CSV')[0] + '.CSV'
答案 1 :(得分:0)
就这么简单:
s = 'Testfile_20190226114536.CSV.986466.1551204043175'
suffix = '.CSV'
s[:s.rindex(suffix) + len(suffix)]
=> 'Testfile_20190226114536.CSV'
答案 2 :(得分:0)
您可以使用re.sub
:
import re
result = re.sub('(?<=\.CSV)[\w\W]+', '', 'Testfile_20190226114536.CSV.986466.1551204043175')
输出:
'Testfile_20190226114536.CSV'
答案 3 :(得分:0)
简单的方法是这个
您所有文件的中间都有这个“ CSV”吗?
您可以尝试拆分并加入您的姓名,如下所示:
name = "Testfile_20190226114536.CSV.986466.1551204043175"
print ".".join(name.split(".")[0:2])
答案 4 :(得分:0)
下面是查看发生什么情况的步骤
>>> 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
功能齐全:
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'