0

I'm trying to list the files in my directory. The directory is /home/user/Desktop/Test/ Within Test, there are 3 folders, a,b,c and within each of the folders a,b,c there are 10 gz files numbered in order 1-10

import os
subdir=os.walk("/home/user/Desktop/Test")
for i in subdir:
    for dir in i:
        print dir

I get an output of

a
b
c

I want to get

1.gz
2.gz
3.gz
4.gz
5.gz
6.gz
7.gz
8.gz
9.gz
10.gz

Where was i wrong?

Jeugasce
  • 197
  • 1
  • 3
  • 11

1 Answers1

2

Read the docs. By typing help(os.walk), you will find this example:

import os
from os.path import join, getsize

for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum([getsize(join(root, name)) for name in files]),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

So if you want to list all the files in your folder, do:

import os

relative_dirnames = ['a', 'b', 'c']
path = '/home/user/Desktop/Test'
dirs_to_list = [os.path.join(path, s) for s in relative_dirnames]

for d in dirs_to_list:
    for _, __, files in os.walk(d):
        print 'Folder: {}'.format(d)
        for f in files:
            print f
        break
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40