python - 列出当前目录的上次创建日期

标签 python python-3.x

我以前从未编写过 Python,并且有一项作业无法完成。 这就是我需要做的。列出给定文件夹中创建的所有文件名称、大小、日期。过滤文件大小(您可以执行 =、> 或 <),这取决于您或一个范围。该脚本应检查并验证文件夹名称和大小。 该脚本应循环,直到在所有子文件夹中找到大于指定大小的所有文件。

我已经能够获取文件列表和大小,但仅此而已。

这就是我到目前为止所拥有的。

import os
Path = os.getcwd()
Files = list(os.listdir(Path))

Dict = dict()
for Allfiles in Files: 
    size = os.stat(Allfiles)
    Dict[Allfiles] = size

for item in Dict:
    print("{:30s} {:d} Bytes".format(item,Dict[item].st_size))

最佳答案

我认为你应该记住以下事情。

  1. 您需要处理所有子目录。您可以使用递归或迭代方法来完成此操作。我更喜欢第一个,如下所示:
def get_all_files(path_to_dir: str) -> dict:
    result = dict()
    for file_name in os.listdir(path_to_dir):
        full_path = os.path.join(path_to_dir, file_name)
        if os.path.isdir(full_path):
            result.update(get_all_files(full_path))
        else:
            result[full_path] = "<info-about-file>"
    return result

迭代看起来非常相似。

  • 您需要获取有关特定文件的信息。 os.stat 返回所有必要的数据:st_size 表示大小,st_ctime 表示创建时间(以秒为单位)。您可以使用 datetime.datetime.fromtimestamp 将秒转换为可读格式。

  • 还需要大小比较的功能。例如

  • def is_need_to_print_file(size: int, min_size: int=0, max_size: int=-1) -> bool:
        if size < min_size:
            return False
        if max_size != -1 and size > max_size:
            return False
        return True
    

    如果min_size等于max_size,将检查确切的值。

  • 函数os.path.exists提供目录路径验证功能。
  • 关于python - 列出当前目录的上次创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526219/

    相关文章:

    python-3.x - 从图纸中提取信息

    python - 一些帮助理解异步 USB 操作与 libusb-1.0 和 ctypes

    python - 当存在 python 2.7 时,使用 python 3.8 创建虚拟环境

    python - 在 Python 中使用 lambda 的 tkinter 按钮命令

    python-3.x - Python/Tkinter : ModuleNotFoundError: No module named '_tkinter'

    python - 在一个字典中创建多个动态字典

    python - conda搜索最旧版本的numpy,受限于Python版本

    python - 如何使用 read 方法在 Python 中将字符转换为行

    python - 在python上运行elasticsearch和kibana时出现回溯错误

    python - 如何选择某个位置将字符串拆分为 "_"?