简体   繁体   中英

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. 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 . 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. 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.

If you are using python 2.x you can use :

commands.getoutput("ls –lR") 

for python 3.0 you can try :

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.

Ex:

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

This will give you exactly the same output as ls -lR in your current dir. Then it's up to you to filter whatever you need from there!

To change current dir use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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