Files and directories in Python on Linux

I am looking for code in python that allows me to take a directory and create a list similar to "ls -lR" containing all the files in the directory. and sub-dir. in tabular form with their names, size, last modified date, permissions, users, etc.

As well as the total size of all files in directories and subdirectories.

I used statistics on time, time, sizes and permissions and added the same in the lists that I created the tables. But find the file name, perm, owner and group. If I could get cleaner code?

+4
source share
4 answers

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 this helps!

EDIT

Commands.getoutput and subprocess.check_output will return the result from the command that you used as a parameter.

Example:

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

This will give you exactly the same result as ls -lR in the current directory. Then it is up to you to filter out everything you need from there!

To change the current directory, use os.chdir (/ wish / dir).

+3
source

To move files recursively, you can use os.walk . This will let you know all the file names you need.

Once you have the file names, you can continue to use os.stat to get the user and group IDs. Regarding access rights, I think there is no way to get them directly using the standard library, but you can use os.access to check permissions one by one to find out which ones are installed.

+5
source

You can navigate in a directory using os.stat as a reference to jcollado, and if you want to use the search pattern to search, use glob in that directory.

+1
source
 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 
0
source

Source: https://habr.com/ru/post/1398777/


All Articles