欢迎访问宙启技术站
智能推送

利用posixpath.lexists()函数判断文件或目录的最后访问时间

发布时间:2023-12-27 23:54:21

在Python中,可以使用posixpath.lexists()函数来判断文件或目录是否存在以及获取文件或目录的最后访问时间。posixpath.lexists()函数可以接受一个路径作为参数,并返回一个布尔值,表示该路径是否存在。如果存在,则可以使用os.path.getatime()函数获取路径的最后访问时间。

下面是一个使用posixpath.lexists()函数判断文件或目录的存在以及获取最后访问时间的示例:

import os
import posixpath

def check_file_existence(path):
    if posixpath.lexists(path):
        print(f"The file or directory {path} exists.")
        return True
    else:
        print(f"The file or directory {path} does not exist.")
        return False

def get_last_access_time(path):
    if check_file_existence(path):
        try:
            last_access_time = os.path.getatime(path)
            print(f"The last access time of {path} is {last_access_time}.")
        except FileNotFoundError:
            print(f"Could not get the last access time of {path}.")
    else:
        print(f"Cannot get the last access time of {path} because it does not exist.")

# 示例使用的路径
file_path = "path/to/file.txt"
dir_path = "path/to/directory"

# 检查文件存在性并获取最后访问时间
get_last_access_time(file_path)
get_last_access_time(dir_path)

在以上示例中,首先定义了两个函数check_file_existence()get_last_access_time()

check_file_existence()函数使用posixpath.lexists()函数来判断文件或目录的存在性,如果存在,则返回True,否则返回False。在函数中,我们使用了if语句来判断路径是否存在,并根据结果输出相应的信息。

get_last_access_time()函数则是用来获取文件或目录的最后访问时间的。在函数中,首先调用check_file_existence()函数来检查路径的存在性。如果路径存在,则使用os.path.getatime()函数来获取路径的最后访问时间,并将其输出。

注意,os.path.getatime()函数返回的是一个时间戳,表示时间的秒数。如果需要将其转换为日期时间格式,可以使用datetime模块进行转换。

在示例中,我们给出了两个路径:一个是文件路径file_path,另一个是目录路径dir_path。我们调用get_last_access_time()函数来获取它们的最后访问时间。

请根据实际情况将示例中的路径替换为真实的路径,然后运行该示例,就可以输出文件或目录的存在性以及最后访问时间。