【问题标题】:What does os.sep do in this function?os.sep 在这个函数中做了什么?
【发布时间】:2020-11-12 09:18:54
【问题描述】:
def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        # print(dirs)
        if dir!= '.git':
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ' * 4 * (level)
            print('{}{}/'.format(indent, os.path.basename(root)))
            subindent = ' ' * 4 * (level + 1)
            for f in files:
                print('{}{}'.format(subindent, f))

我不明白 level = root.replace(startpath, '').count(os.sep) 是如何工作的,请详细解释一下。

【问题讨论】:

  • os.sep 是一种跨平台获取路径分隔符的方式。
  • 你知道replace 是做什么的吗?你知道count 做什么吗?你知道os.sep是什么吗?
  • 来自文档 - os.sep - 操作系统用来分隔路径名组件的字符。这是 '/' 对于 POSIX 和 '\\' 对于 Windows。
  • 查看 python count() 的文档。

标签: python file operating-system


【解决方案1】:

关于os.sep来自Docs

The character used by the operating system to separate pathname components. This is '/' for POSIX and '\' for Windows.

来自help(str.count)

Help on method_descriptor:

count(...)
   S.count(sub[, start[, end]]) -> int

   Return the number of non-overlapping occurrences of substring sub in
   string S[start:end].  Optional arguments start and end are
   interpreted as in slice notation.

所以它返回路径字符串中路径分隔符的数量。

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多