python处理文件

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值