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

Question:

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))
Asked By: Zoofa

||

Answers:

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.

Answered By: user19642323
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.