0

I am trying to make my own os walk function. but the initial part is failing to categorize files and folders into two directories. Instead, all files and folders are listed in both list

import os
path = '/root/Downloads'
files=folders=[]
dirs = os.listdir(path)
for dir in dirs:
    if os.path.isfile(dir):
        files.append(dir)
    else:
        folders.append(dir)
ashwin
  • 17
  • 5

1 Answers1

1

Initially, I thought it was just because you'd declared both files and folders to point to the same instance of a empty list. As the comments below show, this isn't the whole story. I don't know why isfile/isdir don't work, but changing listdir to scandir does. So, your code becomes:

import os
path = '/root/Downloads'
files=[]
folders=[]
dirs = os.scandir(path)
for dir in dirs:
    if os.path.isdir(dir):
        folders.append(dir)
    else:
        files.append(dir)
Nick
  • 4,820
  • 18
  • 31
  • 47