【问题标题】:read string backwards and terminate at first '/'向后读取字符串并在第一个'/'处终止
【发布时间】:2009-11-02 08:42:14
【问题描述】:

我只想提取路径的文件名部分。我下面的代码有效,但我想知道更好的(pythonic)方法是什么。

filename = ''
    tmppath = '/dir1/dir2/dir3/file.exe'
    for i in reversed(tmppath):
        if i != '/':
            filename += str(i)
        else:
            break
    a = filename[::-1]
    print a

【问题讨论】:

  • 这个问题措辞不当,应该是“如何从路径中提取文件名。”
  • 你用什么书或教程来学习 Python?

标签: python path


【解决方案1】:

试试:

#!/usr/bin/python
import os.path
path = '/dir1/dir2/dir3/file.exe'
name = os.path.basename(path)
print name

【讨论】:

    【解决方案2】:

    您最好为此使用标准库:

    >>> tmppath = '/dir1/dir2/dir3/file.exe'
    >>> import os.path
    >>> os.path.basename(tmppath)
    'file.exe'
    

    【讨论】:

      【解决方案3】:

      使用os.path.basename(..) 函数。

      【讨论】:

        【解决方案4】:
        >>> import os
        >>> path = '/dir1/dir2/dir3/file.exe'
        >>> path.split(os.sep)
        ['', 'dir1', 'dir2', 'dir3', 'file.exe']
        >>> path.split(os.sep)[-1]
        'file.exe'
        >>>
        

        【讨论】:

          【解决方案5】:

          现有答案对于您的“真正的潜在问题”(路径操作)是正确的。对于您标题中的问题(当然可以推广到其他字符),有什么帮助是 rsplit 字符串方法:

          >>> s='some/stuff/with/many/slashes'
          >>> s.rsplit('/', 1)
          ['some/stuff/with/many', 'slashes']
          >>> s.rsplit('/', 1)[1]
          'slashes'
          >>> 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-16
            • 1970-01-01
            • 1970-01-01
            • 2022-11-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-06-29
            相关资源
            最近更新 更多