使用 Python 递归获取所有文件(带有绝对路径)的列表及其 uid

Getting a list of all files (with absolute path) recursively and their uid with Python

我正在尝试编写一个 python 脚本以递归地列出给定目录中具有绝对路径的所有文件,并在它们前面列出它们的 UID 和文件所有者。 (类似: ls -lR ) 我写了这个但是它在执行结束时给了我一个错误:

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)
import os
import glob

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

需要 Python 3.5 或更高版本 Use a Glob() to find files recursively in Python?

files 只是文件名本身,不是 从您当前位置到文件的路径。

尝试

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)

os.path.abspath() 并不像您想象的那样。它或多或少只是将 getcwd() 的结果添加到您传递的字符串中,它不知道该文件的实际位置。因此,当您的循环到达子目录中的名称时,abspath() 是错误的,因为当前目录仍然是上面的级别。

您可以从 os.walk 的输出中获取正确的目录名称,请参阅文档 here