See also std.file.
(1) os.listdir()
|
import os
def main():
entries = os.listdir(".")
# get all files in the current dir.
# (non-recursively)
for e in entries:
if os.path.isfile(e):
print(e)
|
import std.stdio;
import std.file;
import std.path; // baseName()
import std.algorithm; // map()
void main()
{
// .: current directory
// *: collect everything
// SpanMode.shallow: non-recursively
auto entries = dirEntries(".", "*", SpanMode.shallow);
// get all files in the current dir. (non-recursively)
foreach (e; entries)
{
if (isFile(e))
{
writeln(e); // ./main.py
// writeln(e.baseName); // main.py
}
}
}
|
main.py
main.d
test.txt
|
./main.py
./main.d
./test.txt
|
In the D version, we also get the relative path in front of the filename, e.g. ./main.py
. If you don't need that prefix, use the second version with baseName()
.
Glob
Let's say you want to collect all the .txt
files in the current directory.
(2) glob.glob("*.txt")
|
import glob
def main():
entries = glob.glob("*.txt")
for e in entries:
print(e)
|
import std.stdio;
import std.file; // dirEntries()
import std.path; // baseName()
void main()
{
// .: current directory
// *.txt: wildcard, what to collect
// SpanMode.shallow: non-recursively
auto entries = dirEntries(".", "*.txt", SpanMode.shallow);
foreach (e; entries)
{
writeln(e);
// writeln(e.baseName);
}
}
|
in.txt
out.txt
test.txt
|
./in.txt
./out.txt
./test.txt
|
In the D version, we also get the relative path in front of the filename, e.g. ./main.py
. If you don't need that prefix, use the second version with baseName()
.