Author Topic: [Python] Simple script to delete files in a directory  (Read 1060 times)

0 Members and 1 Guest are viewing this topic.

Offline Bean

  • NULL
  • Posts: 2
  • Cookies: 0
    • View Profile
[Python] Simple script to delete files in a directory
« on: August 18, 2015, 01:22:55 am »
Code: [Select]
import os


def loop_dir(file_path):
   for root, dirs, files in os.walk(file_path, topdown=False):
      for name in files:
         if name.lower().endswith(".torrent"):
            print "Deleting: " + name
            os.remove(file_path + name)
         
loop_dir("C:\\Users\\[Redacted]\\Downloads\\")

I basically made this to get rid of all of the files with the .torrent extension in my downloads folder. Some time when I get the time to improve it I plan on making it just delete them automatically once they collect (like 7+ files with that extension). This script could easily be modified to just take the directory as a CLI arg, but this is mainly for my own personal use and laziness.

I know that this is probably not the most efficient way of doing this, but it gets the job done. Any ideas or alternate ways to do this would be greatly appreciated as I am here to learn.
-------------------------------------------------------------------------------------------------

Okay guys, here is a better version of it. I didn't hard code anything (stupid mistake on my part) and it's much more verbose. I made it so you can delete any extension given to it and you can specify file path as well as whether or not you want reassurance of the files being deleted.
Code: [Select]
import os
import getopt
import sys


def help():
print "Delete files from dir based on extension\n"
print "Usage: DeleteTorrent.py -v [Directory] [Extenstion]\n"
print "-v --validate - validates every file you"
print "                                 wish to delete. Y/n prompt.\n"
print "-nv --novalidation          - no validation after every file."


#y/n after every file
def loop_dir_validation():
file_path = sys.argv[2]
extension = sys.argv[3]
dir_of_files = os.path.join(file_path)

for root, dirs, files in os.walk(dir_of_files, topdown=False):
for name in files:
if name.lower().endswith(str(extension)):
print "Deleting: " + name
file_to_del = os.path.join(dir_of_files, name)

print "Are you sure you want to delete these files? (y/n)"
decision = raw_input("(Y/n) ")

if decision == "y" or decision == "Y":
print "OK, Deleting..."
os.remove(file_to_del)
else:
print "Exiting..."
quit()


#no y/n
def loop_dir_novalidation(extension):
file_path = sys.argv[2]
extension = sys.argv[3]
dir_of_files = os.path.join(file_path)

for root, dirs, files in os.walk(dir_of_files, topdown=False):
for name in files:
if name.lower().endswith(str(extension)):
print "Deleting: " + name
file_to_del = os.path.join(dir_of_files, name)
os.remove(file_to_del)



def main():
if not len(sys.argv[1:]):
help()

#get cli options
try:
opts, args = getopt.getopt(sys.argv[1:],"hvnv",
["help", "validate", "novalidation"])

except getopt.GetoptError as err:
print str(err)
help()

for o, a in opts:
if o in ("-h", "--help"):
help()
elif o in ("-v", "--validate"):
loop_dir_validation()
elif o in ("-nv", "--novalidation"):
loop_dir_novalidation(extension)
else:
print "Invalid option"
help()


main()


The help function might come up out of line. That's about the only thing I know of that will be out of place. Any more suggestions would be cool. I know this isn't considered a "real" project, but it does the job as far as getting me back into coding. I apologize for the slop at the top of the page.  :(
« Last Edit: August 20, 2015, 02:30:28 am by Bean »

Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: [Python] Simple script to delete files in a directory
« Reply #1 on: August 18, 2015, 01:58:14 am »
No shit this ca be easily found on google though it is fine to get your python hands dirty again.

Might i advise that you would have made it more versatile such that the file extension is supplied at the commandline or something or a better nifty way like using signals then that would be getting your hands dirty again.
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline iTpHo3NiX

  • EZ's Pirate Captain
  • Administrator
  • Titan
  • *
  • Posts: 2920
  • Cookies: 328
    • View Profile
    • EvilZone
Re: [Python] Simple script to delete files in a directory
« Reply #2 on: August 18, 2015, 02:38:14 am »
rm -rf ~/downloads/*.torrent

In a bash script with a crontab to run every so often...
[09:27] (+lenoch) iTpHo3NiX can even manipulate me to suck dick
[09:27] (+lenoch) oh no that's voluntary
[09:27] (+lenoch) sorry

Offline Fur

  • Knight
  • **
  • Posts: 216
  • Cookies: 34
    • View Profile
Re: [Python] Simple script to delete files in a directory
« Reply #3 on: August 18, 2015, 02:47:34 am »
rm -rf ~/downloads/*.torrent
Or
Code: [Select]
del /s %USERPROFILE%\Downloads\*.torrent under Windows (IIRC) since the directory in his code implies he's using Windows.
« Last Edit: August 18, 2015, 02:54:04 am by Fur »

Offline Bean

  • NULL
  • Posts: 2
  • Cookies: 0
    • View Profile
Re: [Python] Simple script to delete files in a directory
« Reply #4 on: August 18, 2015, 03:07:20 am »
No shit this ca be easily found on google though it is fine to get your python hands dirty again.

Might i advise that you would have made it more versatile such that the file extension is supplied at the commandline or something or a better nifty way like using signals then that would be getting your hands dirty again.

Yes, I am aware it can be found through google. I haven't written a line of code in like a year or two, so this is me getting back at it. I was gonna run it through commandline, but it was a quick solution. I will make changes although I'm not too familiar with signals (reading through the pydoc now).

Or
Code: [Select]
del /s %USERPROFILE%\Downloads\*.torrent under Windows (IIRC) since the directory in his code implies he's using Windows.

Yep, I'm in windows as of now.

Offline iTpHo3NiX

  • EZ's Pirate Captain
  • Administrator
  • Titan
  • *
  • Posts: 2920
  • Cookies: 328
    • View Profile
    • EvilZone
Re: [Python] Simple script to delete files in a directory
« Reply #5 on: August 18, 2015, 03:18:26 am »
Lsimhbiwfefmtalol at hardcoded directories
[09:27] (+lenoch) iTpHo3NiX can even manipulate me to suck dick
[09:27] (+lenoch) oh no that's voluntary
[09:27] (+lenoch) sorry

Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: [Python] Simple script to delete files in a directory
« Reply #6 on: August 18, 2015, 07:57:35 pm »
Lsimhbiwfefmtalol
For real, what is that in full?^^^

Yes, I am aware it can be found through google. I haven't written a line of code in like a year or two, so this is me getting back at it. I was gonna run it through commandline, but it was a quick solution. I will make changes although I'm not too familiar with signals.
Do you the average number of projects people have open for coding? And do you at how many point someone else would have declared them complete and ready for public review? But the guys have to beat their own deadlines to deliver quality. No one is on you neck here to deliver anything until you are ready and you better deliver quality or people won't respect you.
There is something called git and your hard drive that won't mind acting as you diary but be sure you lay a good ground here for people to respect you and your coding journey than takes us for a personal diary. Get a real project under your gloves for a change.

^^That was harsh! :P
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline iTpHo3NiX

  • EZ's Pirate Captain
  • Administrator
  • Titan
  • *
  • Posts: 2920
  • Cookies: 328
    • View Profile
    • EvilZone
Re: [Python] Simple script to delete files in a directory
« Reply #7 on: August 18, 2015, 10:37:27 pm »
For real, what is that in full?^^^

Laughing silently in my head because it wasn't funny enough for me to actually laugh out loud

I have it set up as a keyboard shortcut for when I type lol. Because more than half the time I laugh in my head whenever I type lol
« Last Edit: August 18, 2015, 10:39:05 pm by DeepCopy »
[09:27] (+lenoch) iTpHo3NiX can even manipulate me to suck dick
[09:27] (+lenoch) oh no that's voluntary
[09:27] (+lenoch) sorry

Offline 0E 800

  • Not a VIP
  • VIP
  • Baron
  • *
  • Posts: 895
  • Cookies: 131
  • • тнε ιηтεяηεт ιs мү яεcүcℓε-вιη •
    • View Profile
Re: [Python] Simple script to delete files in a directory
« Reply #8 on: August 18, 2015, 10:41:35 pm »
Laughing silently in my head because it wasn't funny enough for me to actually laugh out loud

I have it set up as a keyboard shortcut for when I type lol. Because more than half the time I laugh in my head whenever I type lol

Hah, nice. I mostly doubt that anyone that types 'lol' is actually laughing out loud. Even more so for the 'rotfl' types.

« Last Edit: August 18, 2015, 10:41:50 pm by 0E 800 »
The invariable mark of wisdom is to see the miraculous in the common.