Skip to content

Commit 5ef0384

Browse files
authored
stdlib/os: add listdir
1 parent 0cc4032 commit 5ef0384

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

stdlib/os/os.go

+57
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ func init() {
5353
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
5454
py.MustNewMethod("getenv", getenv, 0, "Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str."),
5555
py.MustNewMethod("getpid", getpid, 0, "Return the current process id."),
56+
py.MustNewMethod("listdir", listDir, 0, listDir_doc),
5657
py.MustNewMethod("makedirs", makedirs, 0, makedirs_doc),
5758
py.MustNewMethod("mkdir", mkdir, 0, mkdir_doc),
5859
py.MustNewMethod("putenv", putenv, 0, "Set the environment variable named key to the string value."),
@@ -234,6 +235,62 @@ func getpid(self py.Object, args py.Tuple) (py.Object, error) {
234235
return py.Int(os.Getpid()), nil
235236
}
236237

238+
const listDir_doc = `
239+
Return a list containing the names of the files in the directory.
240+
241+
path can be specified as either str, bytes. If path is bytes, the filenames
242+
returned will also be bytes; in all other circumstances
243+
the filenames returned will be str.
244+
If path is None, uses the path='.'.
245+
246+
The list is in arbitrary order. It does not include the special
247+
entries '.' and '..' even if they are present in the directory.
248+
`
249+
250+
func listDir(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
251+
var (
252+
path py.Object = py.None
253+
)
254+
err := py.ParseTupleAndKeywords(args, kwargs, "|z*:listdir", []string{"path"}, &path)
255+
if err != nil {
256+
return nil, err
257+
}
258+
259+
if path == py.None {
260+
cwd, err := os.Getwd()
261+
if err != nil {
262+
return nil, py.ExceptionNewf(py.OSError, "cannot get cwd, error %s", err.Error())
263+
}
264+
path = py.String(cwd)
265+
}
266+
267+
dirName := ""
268+
returnsBytes := false
269+
switch v := path.(type) {
270+
case py.String:
271+
dirName = string(v)
272+
case py.Bytes:
273+
dirName = string(v)
274+
returnsBytes = true
275+
default:
276+
return nil, py.ExceptionNewf(py.TypeError, "str or bytes expected, not %T", path)
277+
}
278+
279+
dirEntries, err := os.ReadDir(dirName)
280+
if err != nil {
281+
return nil, py.ExceptionNewf(py.OSError, "cannot read directory %s, error %s", dirName, err.Error())
282+
}
283+
result := py.NewListSized(len(dirEntries))
284+
for i, dirEntry := range dirEntries {
285+
if returnsBytes {
286+
result.Items[i] = py.Bytes(dirEntry.Name())
287+
} else {
288+
result.Items[i] = py.String(dirEntry.Name())
289+
}
290+
}
291+
return result, nil
292+
}
293+
237294
const makedirs_doc = `makedirs(name [, mode=0o777][, exist_ok=False])
238295
239296
Super-mkdir; create a leaf directory and all intermediate ones. Works like

stdlib/os/testdata/test.py

+6
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,11 @@
151151
os.mkdir(dir1)
152152
os.mkdir(dir2)
153153
os.mkdir(dir11)
154+
print(os.listdir(bytes(top, "utf-8")))
155+
orig = os.getcwd()
156+
os.chdir(top)
157+
print(os.listdir())
158+
os.chdir(orig)
154159
os.removedirs(dir1)
155160
try:
156161
os.mkdir(dir11)
@@ -181,6 +186,7 @@
181186
print("INVALID error caught: %s" % e)
182187
os.remove(fname)
183188
os.rmdir(dir2)
189+
print(os.listdir(top))
184190
except Exception as e:
185191
print("could not create/remove directories: %s" % e)
186192
finally:

stdlib/os/testdata/test_golden.txt

+3
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@ os.linesep: [OK]
2525
os.devnull: [OK]
2626
os.altsep: [OK]
2727
caught: OSError: 'Bad file descriptor' [OK]
28+
[b'dir1', b'dir2']
29+
['dir1', 'dir2']
2830
caught: SystemError - no such file or directory [OK]
2931
caught: FileExistsError [OK]
3032
caught: SystemError - directory not empty [OK]
33+
['dir1']
3134
os.{mkdir,rmdir,remove,removedirs} worked as expected
3235
OK

0 commit comments

Comments
 (0)