Files
Python_CookBook_repo/5.文件与IO/12.检测文件是否存在.py

22 lines
1.1 KiB
Python
Raw Normal View History

2025-09-10 16:12:45 +08:00
import os
if __name__ == '__main__':
# 如果想知道文件是否存在可以使用os.path.exists
# 这个函数返回一个布尔值如果存在就返回T否则返回F
print(os.path.exists("file_not_exists.txt"))
print(os.path.exists("5.文件与IO/1.somefile.txt"))
# 判断是不是一个文件可以使用isfile方法
print(os.path.isfile("5.文件与IO/1.somefile.txt"))
# 判断是不是一个文件夹可以使用isdir方法
print(os.path.isdir("5.文件与IO"))
# 判断是不是一个软连接可以使用islink方法
print(os.path.isdir("5.文件与IO"))
# 想要知道islink的快捷方式指向的地址可以使用realpath方法
print(os.path.realpath("5.文件与IO"))
# os.path模块可以解决大部分路径问题包括切片、判断、拼接等唯一注意的就是记得给python程序访问路径的权限
# 如果要得到大小和修改日期,也有如下解决方案:
os.path.getsize("5.文件与IO/1.somefile.txt")
os.path.getmtime("5.文件与IO/1.somefile.txt")