1

I am trying to write a python script to list all files with absolute path in a given directory recursively and list their UID and file owners in front of them. (something like: ls -lR ) I wrote this one but it gives me an error at the end of execution:

import os
for folder, subfolders, files in os.walk(os.getcwd()):
    for file in files:
        filePath = os.path.abspath(file)
        print(filePath, os.stat(file).st_uid)
Debian
  • 23
  • 1
  • 3

3 Answers3

5
import os
import glob

for filename in glob.iglob('./**/*', recursive=True):
    print(os.path.abspath(filename), os.stat(filename).st_uid)

Needs Python 3.5 or higher Use a Glob() to find files recursively in Python?

humodz
  • 600
  • 3
  • 8
  • Thank you so much #humodz ! That's exactly what I am looking for. Is there any way to store the out put in to the database (mysql or sqligh) ? – Debian Feb 15 '18 at 16:34
3

files are just the filenames themselves, not the path to the files from your current location.

Try

import os
for folder, subfolders, files in os.walk(os.getcwd()):
    for file in files:
        filePath = os.path.abspath(os.path.join(folder, file))
        print(filePath, os.stat(file).st_uid)
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
1

os.path.abspath() doesn't do what you think it does. It more or less just prepends the result of getcwd() to the string you pass, it doesn't know anything about where that file actually is. So when your loop gets to a name in a subdirectory, the abspath() is wrong, since the current directory is still the level above.

You can get the correct directory name from the output of os.walk, see the documentation here.

Personman
  • 2,324
  • 1
  • 16
  • 27
  • I got it now! thanks for correcting me. I didn't know about "glob" module. It saved me lots of time/code. – Debian Feb 15 '18 at 16:40
  • If your question is answered, please click the checkmark next to one of the answers to accept it! – Personman Feb 15 '18 at 16:41