Skip to content

Commit a9fd762

Browse files
committed
os: listdir(), walk(): Handle unicode strings properly.
CPython lib reference specifies that listdir() should accept both bytes and str argument, and return value type should match the argument. But no such stipulation is made for walk(), so we just return strings.
1 parent a3495c4 commit a9fd762

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

os/os/__init__.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,13 @@ def ilistdir_ex(path="."):
115115
yield dirent
116116

117117
def listdir(path="."):
118-
is_bytes = type(path) is bytes
118+
is_str = type(path) is not bytes
119119
res = []
120120
for dirent in ilistdir_ex(path):
121-
fname = str(dirent[4].split('\0', 1)[0], "ascii")
122-
if fname != "." and fname != "..":
123-
if is_bytes:
124-
fname = fsencode(fname)
121+
fname = dirent[4].split(b'\0', 1)[0]
122+
if fname != b"." and fname != b"..":
123+
if is_str:
124+
fname = fsdecode(fname)
125125
res.append(fname)
126126
return res
127127

@@ -130,12 +130,12 @@ def walk(top, topdown=True):
130130
dirs = []
131131
for dirent in ilistdir_ex(top):
132132
mode = dirent[3] << 12
133-
fname = str(dirent[4].split('\0', 1)[0], "ascii")
133+
fname = dirent[4].split(b'\0', 1)[0]
134134
if stat_.S_ISDIR(mode):
135-
if fname != "." and fname != "..":
136-
dirs.append(fname)
135+
if fname != b"." and fname != b"..":
136+
dirs.append(fsdecode(fname))
137137
else:
138-
files.append(fname)
138+
files.append(fsdecode(fname))
139139
if topdown:
140140
yield top, dirs, files
141141
for d in dirs:

0 commit comments

Comments
 (0)