SoFunction
Updated on 2024-11-17

python implementation of manipulating files (folders)

This article example for you to share the specific code of pyhton operation file, for your reference, the specific content is as follows

copy_file

Function: Copy all files (folders) under a folder to another folder

#! python 3
# -*- coding:utf-8 -*-
# Autor: GrayMac
import shutil
import os

basefileclass = 'basefile'
#sourcefile: source file path fileclass: source folder destinationfile: destination folder path
def copy_file(sourcefile,fileclass,destinationfile):
  # Iterate through directories and subdirectories
  for filenames in (sourcefile):
    # Get the absolute path to a file or filename
    filepath = (sourcefile,filenames)
    # Determine if it is a folder
    if (filepath):
      if fileclass == basefileclass :
        copy_file(filepath,fileclass + '/' + filenames,destinationfile + '/' + filenames)
      else :
        copy_file(filepath,fileclass,destinationfile + '/' + filenames)
    # Determine if it is a file
    elif (filepath):
     print('Copy %s'% filepath +' To ' + destinationfile)
     # If no folder then recreate
     if not (destinationfile):
       (destinationfile)
     (filepath,destinationfile)
        
copy_file(sourcefile,basefileclass,destinationfile)

zip_file

Function: Compress all files (folders) under a certain folder

#! python 3
# -*- coding:utf-8 -*-
# Autor: GrayMac
import zipfile
import os
#dirpath: path of compressed source file outpath: path of output folder outname: name of output compressed file
basefilepath = 'basefile/'
def zip_file(dirpath,outpath,outname):
  print('Start ZIP ' + dirpath + ' To ' + outname)
  zip = (outpath + outname,"w",zipfile.ZIP_DEFLATED)
  for path,dirnames,filenames in (dirpath):
    # Remove the destination and path, only the files and folders under the destination folder will be compressed.
    fpath = (dirpath,basefilepath)
    for filename in filenames:
      ((path,filename),(fpath,filename))
  ()
  print('ZIP' + outname + 'successed !')
zip_file(dirpath,outpath,outname)

del_file

Function: Delete all files (folders) under a certain folder

#! python 3
# -*- coding:utf-8 -*-
# Autor: GrayMac
import shutil
import os
#path_data Delete folder path
#(path_data) returns a list of relative paths to everything under the current directory
#(file_data) Determines if it is a file or not
#(file_data) Delete file
#(file_data) Delete folder (non-empty)
def del_file(path_data):
  print('Start Delete : ' + path_data)
  for filenames in (path_data) :
    file_data = path_data + "\\" + filenames#Absolute path to everything underneath the current folder
    if (file_data) :
      (file_data)
    else:
      (file_data)
  print('Delete successed !')

This is the whole content of this article.