Python脚本列出Linux系统目录中的文件

这段代码是一个脚本使用osstat模块来获取文件信息,例如文件大小、类型、权限、修改时间、用户和组。脚本还处理符号链接,并捕获文件列表过程中出现的任何错误。文件信息以换行分隔的JSON (ndjson) 格式输出。

脚本接受以下命令行参数:

  • directory:要列出文件的目录路径。
  • count:要查询的文件数量。默认为5。
  • keyword:用于过滤文件名的关键字。这是可选参数。

脚本使用argparse模块解析命令行参数,并调用list_files()函数执行文件列表。list_files()函数接受目录路径、数量和关键字作为参数,并将文件信息返回为ndjson格式。

要使用该脚本,您可以在命令行中使用所需的directory参数运行它。如果要指定countkeyword参数,也可以包含它们。例如:

 

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)

测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值