Python文件与目录操作实战:遍历、删除、重命名、移动与查找

桃夭
桃夭
发布时间:2026-10-13 | 2人浏览过
原创

本文系统总结了Python中对文件和目录的核心操作方法,涵盖遍历目录(含递归)、删除文件与多级文件夹、文件重命名、创建多级文件夹、移动文件、查找指定扩展名文件以及计算文件夹大小等实用功能。结合网盘服务端开发场景,提供完整代码示例与辅助函数,帮助开发者高效处理文件系统任务。

Python文件与目录操作概述

本文详细介绍Python中处理文件和目录的常用方法,供读者参考学习。

Python能够便捷地执行文件的打开、读写、删除等操作,同时也支持对文件夹进行遍历处理。主要功能包括以下几个方面:

1. Python遍历文件目录,支持递归遍历 2. Python删除文件 3. Python对文件进行重命名 4. Python创建文件夹(支持多级层级创建) 5. Python删除文件夹(支持多级层级删除) 6. Python移动文件 7. Python查找文件 8. 获取文件夹的大小

网盘服务端开发中的文件处理实践

以下代码片段源自笔者在开发Python网盘服务端时的实际应用场景,整理记录以便后续查阅。

核心功能代码实现


#coding:utf-8
import StringIO
import json
import os
import time
import glob
import shutil
DATETIMEFORMATER='%Y-%m-%d %X'
#only for windows
RECYCLED_FOLDER_NAME='Recycled'
def dateformat(datetime):
  '''return GMT TIME,need to change to LOCAL TIME'''
  return time.strftime( DATETIMEFORMATER,time.gmtime(datetime) )
def filesizeformat(size):
  ''' Convert file size to string '''
  KBSIZE=1024.00
  strSize='0 Byte'
  if (size < KBSIZE):
    strSize = '%.2f Byte' % (size)
  elif (size >= KBSIZE and size < KBSIZE**2):
    strSize = '%.2f K' % (size / KBSIZE)
  elif (size >= KBSIZE**2 and size < KBSIZE**3):
    strSize = '%.2f M' % (size / KBSIZE / KBSIZE)
  elif (size >= KBSIZE**3):
    strSize = '%.2f G' % (size / KBSIZE / KBSIZE / KBSIZE)
  return strSize
def listdir(path):
  if os.path.isfile(path):
    return '[]'
  allFiles=os.listdir(path)
  retlist=[]
  for cfile in allFiles:
    fileinfo={}
    filepath=(path+os.path.sep+cfile).replace("\\","/")
    if cfile==RECYCLED_FOLDER_NAME:
      continue
    if os.path.isdir(filepath):
      fileinfo['isfile'] = '0'
      fileinfo['size'] = getfoldersize(filepath)
    else:
      fileinfo['isfile'] = '1'
      fileinfo['size'] = os.path.getsize(filepath)
    fileinfo['name'] = cfile
    fileinfo['lastvisittime'] = dateformat( os.path.getatime(filepath) )
    fileinfo['createtime'] = dateformat( os.path.getctime(filepath) )
    fileinfo['lastmodifytime'] = dateformat( os.path.getmtime(filepath) )
    retlist.append(fileinfo)
  retStr=json.dumps(retlist,encoding='utf-8')
  return retStr
def deletefile(path):
  if os.path.exists(path):
    os.remove(path)
def rename(old,new):
  if os.path.exists(old):
    os.rename(old, new)
def checkoutfile(path):
  pass
def checkinfile(path):
  pass
def lockfile(path):
  pass
def unlockfile(path):
  pass
def createfolder(path):
  if not os.path.exists(path):
    os.mkdir(path)
def createfolders(path):
  if not os.path.exists(path):
    os.makedirs(path);
def deletefolder(path):
  if os.path.isdir(path):
    os.rmdir(path)
def retreeExceptionHandler(fun,path,excinfo):
  pass
def deletefolders(path):
#  if os.path.isdir(path):
#    os.removedirs(path)
  shutil.rmtree(path,ignore_errors=False,onerror=retreeExceptionHandler)
def movefile(old,new):
  shutil.move(old, new)
def getfoldersize(path):
  size = 0
  for root, dirs, files in os.walk(path):
    size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
  return size
def searchfile(path,ext):
  returnList=glob.glob1(path, ext)
  return returnList
if __name__=='__main__':
  listdir('c:/vDriver')
  #searchfile('c:/vDriver','*.log')

方法命名与功能对应说明

通过上述代码中函数的命名,即可清晰了解Python操作文件及文件夹的各项方法。

延伸阅读资源推荐

如需进一步了解Python相关技巧,可参考本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》。

希望本文内容对您的Python编程实践有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表