Skip to main content

Command Palette

Search for a command to run...

Show all directory content in python and rust

Updated
1 min read

In Python, you can make use of the Path class from pathlib module:

from pathlib import Path

p = Path("/home/eric")

for item in p.iterdir():
    print(item)

Output:

.rustup
.config
.bash_logout
snap
.cert
.sudo_as_admin_successful
.mozilla
Music
.bashrc
.gnupg
.cache
.pki
Documents
.bash_aliases
.tmux.conf
.vscode
.vimrc
Downloads
.dbus
Templates
Public
.ssh
Pictures
.profile
Desktop
.viminfo
.local
.vim
Videos
.bash_history
.pam_environment
.cargo
.python_history

Rust has something similar: std::path::Path.

Since Python's Path object has an iterdir() method, I naturally tried to use iter method for std::path::Path. But it returns an iterator of path components:

use std::path::Path;

let folder = Path::new("/home/eric");

for component in folder.iter() {
    println!("{:?}", component);
}

Output:

"/"
"home"
"eric"

What I actually want is the read_dir method.

read_dir returns a Result-wrapped iterator of Result-wrapped DirEntry.

They are wrapped in Result<T, err> because reading from disk can sometimes result in an IO error. Since this is not production code, I'll unwrap these Result enums.

use std::path::Path;
use std::fs::DirEntry;

let folder = Path::new("/home/eric");

for item in folder.read_dir().unwrap() {
    let entry: DirEntry = item.unwrap();
    println!("{:?}", entry.file_name());
}

Output (identical to that of Python's output):

.rustup
.config
.bash_logout
snap
.cert
.sudo_as_admin_successful
.mozilla
Music
.bashrc
.gnupg
.cache
.pki
Documents
.bash_aliases
.tmux.conf
.vscode
.vimrc
Downloads
.dbus
Templates
Public
.ssh
Pictures
.profile
Desktop
.viminfo
.local
.vim
Videos
.bash_history
.pam_environment
.cargo
.python_history

More from this blog

Ai與知識債

技術債 technical debt 源自貪快/便宜/方便而採用的技術方案,犧牲可讀性、維護性、測試性、文件完整等等的面向,延後償還技術上的代價 隨著 vibe coding 的普及,另一種債也在慢慢累積:知識債 開發者抱著一個「可以跑就好」的想法就把產品推上架,卻不理解 AI 生成的程式碼到底在做什麼、不知道 AI 的作法到底對不對。前一陣子的鏟子英雄平台個資問題就是案例之一 哈佛教授 Jonathan Zittrain 已經在 2019 年將此現象取名為 intellectual debt,...

Jan 8, 20261 min read

結巴分詞解析三部曲, 第三集

How jieba works, part 3 本篇將用 Part 2 介紹的隱藏式馬可夫模型與 Viterbi 演算法將剩下的字 (大、學、與、老、師、討、論、力、學) 分詞。 字的隱藏狀態 一個人的身體可以有健康、生病的隱藏狀態。那一個字可以有幾種?結巴的程式碼定義了四種隱藏狀態:詞首、詞中、詞尾、以及單獨存在,分別用 B, M, E, S 標示。這四種狀態其實就是字位於詞的不同位置。 例如: 我: S 『我』只有一個字,所以標示 S 單獨存在。 的: S 『的』只有一個字,所以標示...

Aug 19, 20229 min read

結巴分詞解析三部曲, 第二集

How jieba works, part 2 這篇將解釋何謂馬可夫模型 Markov model、隱藏式馬可夫模型 Hidden Markov model (HMM)、與 Viterbi 演算法。 馬可夫模型 Markov model 馬可夫模型是一個用來解釋偽隨機系統的模型。它假設未來事件只受到現在事件影響,不受更早事件影響。 範例:假設你是醫生,從你的臨床經驗來看,一個人身體前一天健康、今天也健康的機率是 0.7;前一天健康、今天生病的機率是 0.3;前一天生病、今天健康的機率是 0.4;...

Aug 19, 20223 min read

Blank Stare

9 posts