简体   繁体   English

Linux上Python中的文件和目录

[英]Files and directories in Python on linux

I am looking for a code in python that allows me to take a directory and create a list similar to “ls –lR” containing all the files in the dir. 我正在寻找python中的代码,它允许我获取一个目录并创建一个类似于“ls -lR”的列表,其中包含目录中的所有文件。 and sub-dir. 和子目录。 in a tabular form with their names, size, date last modified, permissions, users etc. 以表格形式显示其名称,大小,上次修改日期,权限,用户等。

And also the total size of all the files in the directories and sub-directories. 还有目录和子目录中所有文件的总大小。

I have used stats as of now, for the time, size and permissions and have appended the same in lists of which I have made tables. 我已经使用了截至目前的统计数据,时间,大小和权限,并在我已制作表格的列表中添加了相同的数据。 But to find the file name, the perm, owner and group. 但要查找文件名,烫发,所有者和组。 If I could get a neater code? 如果我能得到更整洁的代码?

To traverse files recursively, you can use os.walk . 要递归遍历文件,可以使用os.walk That will let you know all the file names that you need. 这将让您知道您需要的所有文件名。

Once you have the file names, you can keep on using os.stat to get the user and group ids. 获得文件名后,可以继续使用os.stat来获取用户和组ID。 Regarding permissions, I think there isn't any way to get them directly using the standard library, but you can use os.access to test permissions one by one to find out which ones are set. 关于权限,我认为没有任何方法可以直接使用标准库,但您可以使用os.access测试权限,以找出设置的权限。

If you are using python 2.x you can use : 如果你使用的是python 2.x,你可以使用:

commands.getoutput("ls –lR") 

for python 3.0 you can try : 对于python 3.0,你可以尝试:

subprocess.check_output("ls -lR")

Hope it helps! 希望能帮助到你!

EDIT 编辑

Commands.getoutput and subprocess.check_output will return the output from the command you used as parameter. Commands.getoutput和subprocess.check_output将返回您用作参数的命令的输出。

Ex: 例如:

lslr = commands.getoutput("ls –lR") 
print lslr

This will give you exactly the same output as ls -lR in your current dir. 这将为您提供与当前目录中的ls -lR完全相同的输出。 Then it's up to you to filter whatever you need from there! 然后你可以从那里过滤你需要的任何东西!

To change current dir use os.chdir(/desired/dir). 要更改当前目录,请使用os.chdir(/ desired / dir)。

您可以使用jcollado提及的os.stat遍历目录,如果要使用搜索模式进行搜索,则在该目录中使用glob

import os


def iterbrowse(path):
    for home, dirs, files in os.walk(path):
        for filename in files:
            yield os.path.join(home, filename)


for full_name in iterbrowse("/root"):
    print full_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM