Display all filenames from a specific folder

As is the case with the XYZ folder, which contains files with different formats, let's say .txt file, excel file, .py file, etc. i want to display all filename in output using python programming

0


a source to share


3 answers


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

      



See documentation for details

+3


a source


Here's an example that can also help show some of the handy basics of python-dicts {}

, lists []

, small string methods ( split

), module, for example 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 can 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')
>>>

      

+2


a source


import os

XYZ = '.'

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

      

+1


a source







All Articles