S_Zizzle S_Zizzle - 8 months ago 71
Python Question

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()
fileList = [f for f in directory if f.endswith(".txt")]
for f in fileList:
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):
randomNumber = randint(0,9999)
elif start == ("1"):
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.


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")