【问题标题】:Removing the end of a filename in python在python中删除文件名的结尾
【发布时间】:2019-07-21 09:23:16
【问题描述】:

我需要删除以下文件名的结尾:

Testfile_20190226114536.CSV.986466.1551204043175

所以 CSV 之后的所有内容都需要删除,所以我有一个名为:

Testfile_20190226114536.CSV

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 除了子字符串.CSV. 出现在文件名中的某处之外,您是否提前知道文件名?

标签: python string file


【解决方案1】:

假设file_name = "Testfile_20190226114536.CSV.986466.1551204043175"

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

【讨论】:

    【解决方案2】:

    就这么简单:

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

    【讨论】:

    • 我会使用 .CSV 而不是 CSV :)
    【解决方案3】:

    这是查看发生了什么的步骤

    >>> 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'
    

    【讨论】:

      【解决方案4】:

      简单的方法是这样的

      你所有的文件中间都有这个“CSV”吗?

      你可以像这样尝试拆分和加入你的名字:

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

      【讨论】:

        【解决方案5】:

        你可以使用re.sub:

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

        输出:

        'Testfile_20190226114536.CSV'
        

        【讨论】:

          猜你喜欢
          • 2015-06-20
          • 1970-01-01
          • 2011-05-03
          • 2022-01-20
          • 1970-01-01
          • 2018-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多