我如何在Python中获得给定目录中的所有文件(和目录)的列表?
当前回答
我知道这是一个老问题。如果你在linux机器上,这是我遇到的一种简洁的方法。
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
其他回答
如果你需要通配符,也有一个模块。例如:
import glob
glob.glob('./[0-9].*')
将返回如下内容:
['./1.gif', './2.txt']
请在这里查看文档。
这是另一种选择。
os.scandir(path='.')
它返回os的迭代器。对应于path指定目录中的条目(以及文件属性信息)的DirEntry对象。
例子:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.'):
print(entry.name)
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.
Python文档
下面的代码将列出目录和目录下的文件
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
和我一起工作的是萨利赫在本页其他地方的回答的修改版本。
代码如下:
dir = 'given_directory_name'
filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]
你可以使用
os.listdir(path)
参考和更多的操作系统函数看这里:
Python 2文档:https://docs.python.org/2/library/os.html#os.listdir Python 3文档:https://docs.python.org/3/library/os.html#os.listdir
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象