【问题标题】:how to prevent python script from deleting itself? [closed]如何防止python脚本删除自己? [关闭]
【发布时间】:2021-06-05 06:04:38
【问题描述】:

警告使用此文件时可能会删除同一文件夹中的文件

嗨,这是一个用于删除文件的 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)

【问题讨论】:

    标签: python python-3.x delete-file


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    【解决方案2】:

    您获取了所有文件名,然后将其删除。如果只是添加这个简单的步骤... 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)
    

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 2021-04-15
      • 1970-01-01
      • 2014-06-30
      • 2016-12-27
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多