[英]Display all file names from a specific folder
就像有一个文件夹说XYZ,其中包含不同格式的文件,比如说.txt文件,excel文件,.py文件等。我想使用Python编程在输出中显示所有文件名
import glob
glob.glob('XYZ/*')
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.: 这是一个示例,可能还有助于显示python的一些便捷基础-dicts
{}
,lists []
,小字符串技术( split
),类似os
的模块等:
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')
>>>
import os
XYZ = '.'
for item in enumerate(sorted(os.listdir(XYZ))):
print item
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.