Python 列出目录、子目录和文件 [英] Python list directory, subdirectory, and files

查看:47
本文介绍了Python 列出目录、子目录和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本来列出给定目录中的所有目录、子目录和文件.
我试过这个:

import sys,osroot = "/home/patate/directory/"path = os.path.join(root, "targetdirectory")对于 os.walk(path) 中的 r,d,f:对于 f 中的文件:打印 os.path.join(root,file)

不幸的是它不能正常工作.
我得到了所有文件,但没有得到它们的完整路径.

例如,如果 dir 结构是:

<前>/home/patate/directory/targetdirectory/123/456/789/file.txt

它会打印:

<前>/home/patate/directory/targetdirectory/file.txt

我需要的是第一个结果.任何帮助将不胜感激!谢谢.

解决方案

使用os.path.join连接目录和文件名称:

for path, subdirs, files in os.walk(root):对于文件中的名称:打印(os.path.join(路径,名称))

注意在连接中使用 path 而不是 root,因为使用 root 是不正确的.


在 Python 3.4 中,添加了 pathlib 模块以简化路径操作.所以等价于 os.path.join 将是:

pathlib.PurePath(path, name)

pathlib 的优点是你可以在路径上使用各种有用的方法.如果您使用具体的 Path 变体,您还可以通过它们进行实际的操作系统调用,例如切换到目录、删除路径、打开它指向的文件等等.

I'm trying to make a script to list all directory, subdirectory, and files in a given directory.
I tried this:

import sys,os

root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")

for r,d,f in os.walk(path):
    for file in f:
        print os.path.join(root,file)

Unfortunatly it doesn't work properly.
I get all the files, but not their complete paths.

For example if the dir struct would be:

/home/patate/directory/targetdirectory/123/456/789/file.txt

It would print:

/home/patate/directory/targetdirectory/file.txt

What I need is the first result. Any help would be greatly appreciated! Thanks.

解决方案

Use os.path.join to concatenate the directory and file name:

for path, subdirs, files in os.walk(root):
    for name in files:
        print(os.path.join(path, name))

Note the usage of path and not root in the concatenation, since using root would be incorrect.


In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join would be:

pathlib.PurePath(path, name)

The advantage of pathlib is that you can use a variety of useful methods on paths. If you use the concrete Path variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.

这篇关于Python 列出目录、子目录和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆