python判断文件或文件夹是否存在
------------------------------------------------------------------------------------------------------
文件:import
os
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False
文件夹:
import
os
os.path.exists(test_dir)
#True
os.path.exists(no_exist_dir)
#False
python
使用
os
.unlink()和
os
.remove()来删除文件
------------------------------------------------------------------------------------------------------
# -*- coding:utf-
8
-*-
import
os
my_file =
'F:/test.txt'
if
os
.path.exists(my_file):
#删除文件,可使用以下两种方法。
os
.remove(my_file) #
os
.unlink(my_file)
python
删除指定目录下所有文件或修改文件名
------------------------------------------------------------------------------------------------------
#遍历文件夹
for (root,dirs,files) in os.walk(path) :
for item in files :
d = os.path.join(root, item)
#删除文件
os
.remove(
d
)
#修改文件名
name = 'new_name'
os.rename(d, name)
获取文件属性信息
1、获取文件的大小,结果保留两位小数
------------------------------------------------------------------------------------------------------
def FileSize(filePath):
fsize = os.path.getsize(filePath)
fsize = fsize/float(1024*1024) #
,单位为MB
return round(fsize,2)
2、获取文件的访问时间
------------------------------------------------------------------------------------------------------
def FileAccessTime(filePath):
t = os.path.getatime(filePath)#时间戳
return t
3、获取文件的创建时间
------------------------------------------------------------------------------------------------------
def FileCreateTime(filePath):
t = os.path.getctime(filePath)
return t
4、获取文件的修改时间
------------------------------------------------------------------------------------------------------
def FileModifyTime(filePath):
t = os.path.getmtime(filePath)
return t