python 列出文件目录下的文件名

来源:互联网 发布:最好用的编程语言 编辑:程序博客网 时间:2024/05/06 05:05

以后将会陆续写上一些实例,来填充自己python。

下面这个例子是来列出该文件目录下所有带有‘py’后缀的,前缀不是‘__’的文件名:

import os__all__ = []for filename in os.listdir(os.path.dirname(__file__)):    if not filename.startswith("__") and filename.endswith(".py"):        filename = filename.replace(".py", "")        __all__.append(filename)print __all__

注意这个程序的运行,比如该文件你命名为test.py,然后文件下还有其他一些文件,这个时候,如你运行python test.py将会出错。

(1).当"print os.path.dirname(__file__)"所在脚本是以完整路径被运行的, 那么将输出该脚本所在的完整路径,比如:
             python d:\pythonSrc\test\test.py 
             那么将输出 d:\pythonSrc\test
(2).当"print os.path.dirname(__file__)"所在脚本是以相对路径被运行的, 那么将输出空目录,比如:
             python test.py
             那么将输出空字符串
所以以完整路径进行运行,得到列表。

这个例子还可以进行更改,这对于不论是windos还是linux来说,文件操作这一块就非常方便了。

0 0