python接收用户从键盘输入的一个文件名,然后判断该文件是否存在于当前目录

python接收用户从键盘输入的一个文件名,然后判断该文件是否存在于当前目录,如果存在,则输出以下信息:文件的大小、文件创建时间和文件最后访问时间,如果不存在则输出该“文件不存在!”。把key.txt文件拷贝到程序同一目录下进行测试,结果如下所示。(提示:使用os.path.exists()、os.stat()以及time模块里面的localtime()和strftime())

这样?

img

import os
import time
filename=input("请输入文件名:")
if os.path.exists(filename):
    print('文件大小:'+str(os.path.getsize(filename))+'字节')
    t=os.stat(filename)
    print('文件创建时间:'+time.strftime("%Y-%m-%d  %H:%M:%S",time.localtime(t.st_ctime)))
    print('文件最后访问时间:'+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t.st_atime)))
else:
    print("文件不存在!")

有帮助麻烦点下【采纳该答案】,谢谢~~