S_Zizzle S_Zizzle - 1 month ago 20
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()
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.

Answer

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