这段代码是一个脚本使用os
和stat
模块来获取文件信息,例如文件大小、类型、权限、修改时间、用户和组。脚本还处理符号链接,并捕获文件列表过程中出现的任何错误。文件信息以换行分隔的JSON (ndjson) 格式输出。
脚本接受以下命令行参数:
directory
:要列出文件的目录路径。count
:要查询的文件数量。默认为5。keyword
:用于过滤文件名的关键字。这是可选参数。
脚本使用argparse
模块解析命令行参数,并调用list_files()
函数执行文件列表。list_files()
函数接受目录路径、数量和关键字作为参数,并将文件信息返回为ndjson格式。
要使用该脚本,您可以在命令行中使用所需的directory
参数运行它。如果要指定count
或keyword
参数,也可以包含它们。例如:
python list_files.py /path/to/directory --count 10 --keyword test
这将列出指定目录中包含关键字"test"的最多10个文件。
# -*- coding: utf-8 -*-
import os
import stat
import pwd
import json
import argparse
import sys
def list_files(directory, count, keyword):
# 用于存储文件信息的列表
files = []
file_count = 0
# 遍历目录下的文件和文件夹
for filename in os.listdir(directory):
if keyword and keyword not in filename:
continue
file_path = os.path.join(directory, filename)
try:
# 获取文件信息
file_stats = os.stat(file_path)
file_info = {
'name': filename,
'size': file_stats.st_size,
'type': 'directory' if stat.S_ISDIR(file_stats.st_mode) else 'file',
'permission': oct(file_stats.st_mode)[4:],
'mod_time': file_stats.st_mtime,
'user': pwd.getpwuid(file_stats.st_uid).pw_name,
'group': pwd.getpwuid(file_stats.st_gid).pw_name
}
# 判断是否为链接文件
if os.path.islink(file_path):
file_info['type'] = 'link'
target_path = os.readlink(file_path)
file_info['target'] = target_path
files.append(file_info)
file_count += 1
except OSError as e:
error_info = {
'name': filename,
'type': 'directory' if stat.S_ISDIR(file_stats.st_mode) else 'file',
'reason': str(e)
}
if os.path.islink(file_path):
error_info['type'] = 'link'
target_path = os.readlink(file_path)
error_info['target'] = target_path
files.append(error_info)
if file_count == count:
break
# 输出文件信息为ndjson格式
for file_info in files:
json_str = json.dumps(file_info)
try:
# 输出json字符串
print(json_str)
except IOError as e:
# 忽略Broken pipe错误
if e.errno == 32:
sys.exit(0)
else:
raise
if __name__ == "__main__":
# 创建解析器对象
parser = argparse.ArgumentParser(description='List files in a directory')
# 添加文件夹路径参数
parser.add_argument('directory', help='Path to directory')
# 添加查询文件个数参数
parser.add_argument('count', type=int, default=5, nargs='?', help='Number of files to query (default: 5)')
# 添加关键字过滤参数
parser.add_argument('-k', '--keyword', help='Keyword to filter filenames')
# 解析命令行参数
args = parser.parse_args()
# 调用函数进行文件查询
list_files(args.directory, args.count, args.keyword)
测试结果: