【问题标题】:Why does this Python script delete '.txt' files, as well as all the '.tmp' files?为什么这个 Python 脚本会删除“.txt”文件以及所有“.tmp”文件?
【发布时间】:2015-09-04 22:22:04
【问题描述】:

我正在尝试编写一个脚本,该脚本将自动删除特定文件夹中的所有临时文件,我注意到该脚本还删除了该文件夹中的所有 文本文件。谁能解释为什么会这样?

   import os
   path = 'C:\scripts27'
   for root, dirs, files in os.walk(path):
       for currentFile in files:
           print "processing file: " + currentFile
           extensions=('.tmp')
           if any(currentFile.lower().endswith(ext) for ext in extensions):
               os.remove(os.path.join(root, currentFile))

我在 Windows 8.1 PC 64 位上使用 Python 2.7.10 运行此脚本。

谢谢!

【问题讨论】:

    标签: python python-2.7 os.walk os.path


    【解决方案1】:

    我假设您的意思是提供扩展列表。但在您的情况下,extensions 被定义为('.tmp'),它 不是 一个元组,而是一个字符串。这会导致您的代码遍历所有文件并检查以.tmp 结尾的名称,从而删除您的.txt 文件。

    这里的解决方法是将扩展定义为['.tmp']('.tmp',)(注意尾随,)。

    【讨论】:

    • 就是这样!谢谢。
    • @Basper82 - if currentFile.lower().endswith('.tmp'): do stuff.
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 2021-10-28
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多