如何防止 python 脚本删除自身?

how to prevent python script from deleting itself?

警告使用此文件时它会删除 同一文件夹

上的文件

您好,这是一个用于删除文件的 python 3 脚本,我想知道如何防止它自行删除

代码:

import os
import sys
import glob
fileList = glob.glob('*.*')
print(fileList)
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

您可以使用os.path.basename(__file__)获取当前脚本的名称。所以它可以将 filePath 与此进行比较,然后跳过它。

import os
import sys
import glob

current_script = os.path.basename(__file__)
fileList = glob.glob('*.*')
print(fileList)
for filePath in fileList:
    if filePath != current_script:
        try:
            os.remove(filePath)
        except:
            print("Error while deleting file : ", filePath)

您正在获取所有文件名,然后将其删除。如果你只是加上这个简单的步骤... 1.获取所有文件名,2.排除你不想删除的文件名,然后3.删除剩余的文件名。

import os
import sys
import glob

current_script = os.path.basename(__file__)
fileList = glob.glob('*.*')
fileList.remove(current_script)
print(fileList)
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)