Summary of python Operation Method for File Directory

  • 2021-07-01 07:44:31
  • OfStack

This paper describes the operation method of python to file directory with examples. Share it for your reference, as follows:

python can be very convenient to open files, read and write operations, delete operations, but also very convenient to traverse the folder operations. Generally speaking, there are the following aspects:

1. python traverses the file directory, recursively, of course
2. python Delete Files
3. python renames files
4. python Create Folder (Multiple Level Creation)
5. python Delete Folder (Multiple Level Delete)
6. python Move Files
7. python Find Files
8. Get folder size

The following code is I use python to do a network disk server when some of the methods used, recorded for future reference.


#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')

Above the code, according to the method of naming, you can know python operation files and folders of various methods.

For more readers interested in Python related contents, please check the topics of this site: "Summary of Python File and Directory Operation Skills", "Summary of Python Text File Operation Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: