简体   繁体   English

显示特定文件夹中的所有文件名

[英]Display all file names from a specific folder

就像有一个文件夹说XYZ,其中包含不同格式的文件,比如说.txt文件,excel文件,.py文件等。我想使用Python编程在输出中显示所有文件名

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.

相关问题 将(文件)名称末尾带有特定文本的文件从一个文件夹复制到另一个文件夹 - Copy files with specific text at the end of their (file) names from one folder to other folder 如果文件与另一个文件夹匹配,如何从 1 个文件夹返回所有文件名? - how to return all file names from 1 folder, if files match to another folder? 如何更改文件夹中的所有文件名? - How to change all file names in folder? 从文件夹中的所有文件名中删除数字 - Remove numbers from all files names in a folder Python - 为文件夹中的所有 csv 文件制作新的 csv 文件,名称为 header 以及它们来自的文件 - Python - for all csv files in folder make new csv file with header names and the file they came from 我想将特定文件夹中文件的所有名称添加到列表中 - I want to add all the names of the files in a specific folder to a list Python - 如果文件名包含指定的单词,则将所有文件从一个文件夹移动到另一个文件夹 - Python - move all files from one folder to another if their file names contain specified words Select 文件夹中的特定文件 - Select specific file from a folder Python:获取给定文件夹中特定文件类型的名称 - Python: get the names of specific file types in a given folder 如何使用 python 显示 json 文件中的所有团队名称及其 id - How do display all the team names with their ids from a json file like this with python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM