Python Forum
Delete empty text files [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete empty text files [SOLVED]
#1
Hello everybody,

I have a folder with many text-files, some of them are emtpy but have mutliple lines (for example, someone edited an empty text file, pressed enter and saved the file). I wanted to create a script where it checks every file in a specified path and deletes all those files. I've manged to delete really empty files but haven't gotten to the point, where those multiple-blank-line files have been deleted. This is my code so far:

#!/usr/bin/env python3

#Imports
import sys
import os

#Folder configuration
def remove_empty(path):
    print(list(os.walk(path)))
    for (dirpath, folder_names, files) in os.walk(path):
        for filename in files:
            file_location = dirpath + '/' + filename
            if os.path.isfile(file_location):
                if os.path.getsize(file_location) == 0:
                    os.remove(file_location)

#Deletion
if __name__ == "__main__":
    path = 'C:\Path\to\folder\'
    remove_empty(path)
    
#End
sys.exit()
Reply


Messages In This Thread
Delete empty text files [SOLVED] - by AlphaInc - Jul-09-2022, 12:08 PM
RE: Delete empty text files - by Gribouillis - Jul-09-2022, 01:26 PM
RE: Delete empty text files - by DeaD_EyE - Jul-09-2022, 01:36 PM
RE: Delete empty text files - by AlphaInc - Jul-09-2022, 02:10 PM
RE: Delete empty text files - by Gribouillis - Jul-09-2022, 01:38 PM
RE: Delete empty text files - by DeaD_EyE - Jul-09-2022, 02:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] Loop through directories and files one level down? Winfried 3 261 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
Question [solved] compressing files with python. SpongeB0B 1 681 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 866 Mar-21-2023, 03:43 AM
Last Post: mm309d
  [SOLVED] [sqilte3] Check if column not empty? Winfried 5 1,161 Jan-28-2023, 12:53 PM
Last Post: Winfried
  azure TTS from text files to mp3s mutantGOD 2 1,740 Jan-17-2023, 03:20 AM
Last Post: mutantGOD
  delete all files and subdirectory from a main folder mg24 7 1,656 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  delete all files which contains word sql_Table1 mg24 2 889 Sep-15-2022, 10:05 PM
Last Post: mg24
  [SOLVED] [BeautifulSoup] How to get this text? Winfried 6 2,030 Aug-17-2022, 03:58 PM
Last Post: Winfried
  Writing into 2 text files from the same function paul18fr 4 1,713 Jul-28-2022, 04:34 AM
Last Post: ndc85430
  select files such as text file RolanRoll 2 1,200 Jun-25-2022, 08:07 PM
Last Post: RolanRoll

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020