Show all directory content in python and rust
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