Home > Mobile >  os.walk isn't showing all the files in the given path
os.walk isn't showing all the files in the given path

Time:07-31

I'm trying to make my own backup program but to do so I need to be able to give a directory and be able to get every file that is somewhere deep down in subdirectories to be able to copy them. I tried making a script but it doesn't give me all the files that are in that directory. I used documents as a test and my list with items is 3600 but the amount of files should be 17000. why isn't os.walk showing everything?

import os
data = []
for mdir, dirs, files in os.walk('C:/Users/Name/Documents'):
    data.append(files)
print(data)
print(len(data))

CodePudding user response:

Use data.extend(files) instead of data.append(files).

files is a list of files in a directory. It looks like ["a.txt", "b.html"] and so on. If you use append, you end up with data looking like

[..., ["a.txt", "b.html"]]

whereas I suspect you're after

[..., "a.txt", "b.html"]

Using extend will provide the second behaviour.

  • Related