QBoard » Artificial Intelligence & ML » AI and ML - Python » How to delete a file or folder in Python?

How to delete a file or folder in Python?

  •   September 9, 2021 4:31 PM IST
    0
  • To remove all files in folder

    import os
    import glob
    
    files = glob.glob(os.path.join('path/to/folder/*'))
    files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
    for file in files:
        os.remove(file)

     

    To remove all folders in a directory

    from shutil import rmtree
    import os
    
    // os.path.join()  # current working directory.
    
    for dirct in os.listdir(os.path.join('path/to/folder')):
        rmtree(os.path.join('path/to/folder',dirct))
      September 22, 2021 2:24 PM IST
    0
  • os.remove try this code, it helps.
      September 12, 2021 1:05 AM IST
    0
  • In Python, you can use the os.remove() method to remove files, and the os.rmdir() method to delete an empty folder. If you want to delete a folder with all of its files, you can use the shutil.rmtree() method.

      September 17, 2021 12:22 PM IST
    0