Brijesh
Brijesh

Reputation:

Display all file names from a specific folder

Like there is a folder say XYZ , whcih contain files with diffrent diffrent format let say .txt file, excel file, .py file etc. i want to display in the output all file name using Python programming

Upvotes: 0

Views: 320

Answers (3)

mtasic85
mtasic85

Reputation: 4073

import os

XYZ = '.'

for item in enumerate(sorted(os.listdir(XYZ))):
    print item

Upvotes: 1

unmounted
unmounted

Reputation: 34408

Here is an example that might also help show some of the handy basics of python -- dicts {} , lists [] , little string techniques (split), a module like os, etc.:

bvm@bvm:~/example$ ls
deal.xls    five.xls  france.py  guido.py    make.py      thing.mp3  work2.doc
example.py  four.xls  fun.mp3    letter.doc  thing2.xlsx  what.docx  work45.doc
bvm@bvm:~/example$ python
>>> import os
>>> files = {}
>>> for item in os.listdir('.'):
...     try:
...             files[item.split('.')[1]].append(item)
...     except KeyError:
...             files[item.split('.')[1]] = [item]
... 
>>> files
{'xlsx': ['thing2.xlsx'], 'docx': ['what.docx'], 'doc': ['letter.doc', 
'work45.doc', 'work2.doc'], 'py': ['example.py', 'guido.py', 'make.py', 
'france.py'], 'mp3': ['thing.mp3', 'fun.mp3'], 'xls': ['five.xls',
'deal.xls', 'four.xls']}
>>> files['doc']
['letter.doc', 'work45.doc', 'work2.doc']
>>> files['py']
['example.py', 'guido.py', 'make.py', 'france.py']

For your update question, you might try something like:

>>> for item in enumerate(os.listdir('.')):
...     print item
... 
(0, 'thing.mp3')
(1, 'fun.mp3')
(2, 'example.py')
(3, 'letter.doc')
(4, 'five.xls')
(5, 'guido.py')
(6, 'what.docx')
(7, 'work45.doc')
(8, 'deal.xls')
(9, 'four.xls')
(10, 'make.py')
(11, 'thing2.xlsx')
(12, 'france.py')
(13, 'work2.doc')
>>>

Upvotes: 2

TML
TML

Reputation: 12966

import glob
glob.glob('XYZ/*')

See the documentation for more

Upvotes: 3

Related Questions