删除python中文件名的结尾
我需要删除以下文件名的结尾:删除python中文件名的结尾,python,string,file,Python,String,File,我需要删除以下文件名的结尾: Testfile_20190226114536.CSV.986466.1551204043175 因此,CSV之后的任何内容都需要删除,因此我有一个名为: Testfile_20190226114536.CSV 就这么简单: s = 'Testfile_20190226114536.CSV.986466.1551204043175' suffix = '.CSV' s[:s.rindex(suffix) + len(suffix)] => 'Testfi
Testfile_20190226114536.CSV.986466.1551204043175
因此,CSV之后的任何内容都需要删除,因此我有一个名为:
Testfile_20190226114536.CSV
就这么简单:
s = 'Testfile_20190226114536.CSV.986466.1551204043175'
suffix = '.CSV'
s[:s.rindex(suffix) + len(suffix)]
=> 'Testfile_20190226114536.CSV'
您可以使用re.sub:
假设file_name=Testfile_20190226114536.CSV.986466.1551204043175
简单的方法就是这样
<> P>你的所有文件中间都有这个CSV?
您可以尝试拆分并加入您的姓名,如下所示:
name = "Testfile_20190226114536.CSV.986466.1551204043175"
print ".".join(name.split(".")[0:2])
以下是查看发生了什么的步骤
>>> 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'
到目前为止,您尝试了什么?除了substring.CSV之外,您是否提前知道有关文件名的任何信息。发生在名称中的某个位置?我将使用.CSV而不是CSV:
name = "Testfile_20190226114536.CSV.986466.1551204043175"
print ".".join(name.split(".")[0:2])
>>> 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'