S_Zizzle
S_Zizzle

Reputation: 95

Delete multiple text files in one folder

from random import *
import os

def createFile(randomNumber):
    with open("FileName{}.txt".format(randomNumber), "w") as f:
        f.write("Hello mutha funsta")  

def deleteFile():
    directory = os.getcwd()
    os.chdir(directory)
    fileList = [f for f in directory if f.endswith(".txt")]
    for f in fileList:
        os.remove(f)
print ("All gone!")  

fileName = input("What is the name of the file you want to create? ")
contents = input("What are the contents of the file? ")
start = input("Press enter to start the hax. Enter 1 to delete the products. ")
randomNumber = randint(0, 1)  

while True:
    if start == (""):
        for i in range(0):
            createFile(randomNumber)
            randomNumber = randint(0,9999)
        break
    elif start == ("1"):
        deleteFile()
        break
    else:
        print ("That input was not valid")  

Above is code I've made to create as many text files as I specify (currently set to 0). I am currently adding a feature to remove all the text files created, as my folder now has over 200,000 text files. However, it doesn't work, it runs through without any errors but doesn't actually delete any of the files.

Upvotes: 1

Views: 3490

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140286

that is very wrong:

def deleteFile():
    directory = os.getcwd()
    os.chdir(directory)
    fileList = [f for f in directory if f.endswith(".txt")]
    for f in fileList:
        os.remove(f)
  • you change the directory: not recommended unless you want to run a system call, mostly you change it to the current directory: it has no effect.
  • your list comprehension doesn't scan the directory but a string => f is a character! Since it doesn't end with .txt, your listcomp is empty

To achieve what you want you may just use glob (no need to change the directory and pattern matching is handled automatically):

import glob,os
def deleteFile():
   for f in glob.glob("*.txt"):
      os.remove(f)

this method is portable (Windows, Linux) and does not issue system calls.

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48110

For deleting all the files in the directory with name as FileName{some_thing}.txt, you may use os.system() as:

>>> import os
>>> os.system("rm -rf /path/to/directory/FileName*.txt")

Upvotes: 0

Related Questions