1

I built this little program to simulate 2 libraries I want to compare files with.

The code is this:

import os

path = "C:\Users\\nelson\Desktop\Lib Check"

pc_path = os.path.join(path, "pc")
phone_path = os.path.join(path, "phone")

pc_lib = [filename for path, dirname, filename in os.walk(pc_path)]

print pc_lib

it returns

[['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '8.txt', '9.txt']]

everything is fine except for the fact that the results are in a nested list. Why?

The only way I can stop this is by using

pc_lib = []
for path, dirname, filename in os.walk(pc_path):
    pc_lib.extend(filename)
Nelson
  • 922
  • 1
  • 9
  • 23
  • just for further reference, [here](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) is a neat way of flattening lists in Python. – patrick May 17 '16 at 15:53

3 Answers3

1

filename is a list of files (the name you've used is not intuitive), so the results are expected

for root, dirs, files in os.walk('my/home/directory'):
     print(files)
#['close_button.gif', 'close_button_red.gif'], 
#['toolbar.js']

extend unwraps the argument list and appends the resulting elements to the list that made the call

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

If you want a list of filenames, I would suggest:

[os.path.join(path, filename) 
 for path, dirnames, filenames in os.walk(pc_path)
 for filename in filenames]
Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

os.walk(path) returns an iterator over tuples of (root, dirs, files).

Where

  • root is the path of the current directory relative to the argument of os.walk
  • dirs is a list of all the subdirectories in the current directory
  • files is a list of all normal files in the current directory

If you want a flat list of all files in a filesystem tree, use:

pc_lib = [
    filename for _, _, files in os.walk(pc_path)
    for filename in files
]

You probably want to retain the absolute path, to get thos use:

pc_lib = [
    os.path.join(root, filename)
    for root, _, files in os.walk(pc_path)
    for filename in files
]
MaxNoe
  • 14,470
  • 3
  • 41
  • 46