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")
上面是我创建的代码,用于创建我指定的文本文件(当前设置为0)。我目前正在添加一项功能来删除所有创建的文本文件,因为我的文件夹现在有超过200,000个文本文件。但是,它不起作用,它运行没有任何错误,但实际上并没有删除任何文件。
答案 0 :(得分:0)
这是非常错误的:
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)
f
是一个角色!由于它不以.txt
结尾,因此您的listcomp为空要实现您的目标,您可以使用glob
(无需更改目录,并自动处理模式匹配):
import glob,os
def deleteFile():
for f in glob.glob("*.txt"):
os.remove(f)
此方法是可移植的(Windows,Linux),不会发出系统调用。
答案 1 :(得分:0)
要删除名称为FileName{some_thing}.txt
的目录中的所有文件,您可以使用os.system()
作为:
>>> import os
>>> os.system("rm -rf /path/to/directory/FileName*.txt")