2025-09-10:仓库迁移
This commit is contained in:
22
5.文件与IO/12.检测文件是否存在.py
Normal file
22
5.文件与IO/12.检测文件是否存在.py
Normal file
@@ -0,0 +1,22 @@
|
||||
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")
|
Reference in New Issue
Block a user