我以前从未编写过 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))
最佳答案
我认为你应该记住以下事情。
- 您需要处理所有子目录。您可以使用递归或迭代方法来完成此操作。我更喜欢第一个,如下所示:
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/