如何在 Nim 中列出目录中的项目

How to list items in directory in Nim

我目前正在开发一个应该能够列出目录中的项目的应用程序,但是,在查看了 Nim 中的 OS 模块之后,我找不到一种方法来查看目录中有什么。难不成是还没实现,还是我看错地方才找到这样的功能?

简而言之,我如何才能看到 /home/username/Documents/ 里面的内容?我怎样才能在 Nim 中列出它的内容?

您需要查看 os 模块的 Iterators 部分。

walkDir 和用于此目的的相关迭代器:

iterator walkDir(dir: string; relative = false; checkDir = false): tuple[
    kind: PathComponent, path: string]

Walks over the directory dir and yields for each directory or file in dir. The component type and full path for each item are returned.

你可以这样使用它:

import os

for kind, path in walkDir("/home/username/Documents/"):
  case kind:
  of pcFile:
    echo "File: ", path
  of pcDir:
    echo "Dir: ", path
  of pcLinkToFile:
    echo "Link to file: ", path
  of pcLinkToDir:
    echo "Link to dir: ", path

通过扩展过滤递归遍历子文件夹:

import os
import sequtils

let
    targetFolder = "/home/user/media/"
    targetExt = @[".mp3", ".webm", ".mkv"]

proc scanFolder (tgPath: string, extLst: seq[string]): seq[string] =
    var
        fileNames: seq[string]
        path, name, ext: string
        
    for kind, obj in walkDir tgPath:
    
        if $kind == "pcDir" :
            fileNames = concat(fileNames, scanFolder(obj, extLst))

        (path, name, ext) = splitFile(obj)

        if ext in extLst:
            fileNames.add(obj)

    return fileNames 
            

var fileList = scanFolder(targetFolder, targetExt)   

for f in fileList:
    echo f