发生错误时,删除目录中所有.csv文件的Python脚本不起作用

nx7onnlm  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(114)

我有一个脚本,删除所有csv文件exept 2类型。我有一个文件,我不能删除,我试图删除它,但它只是不工作,即使我是管理员。所以我的脚本需要跳过这个文件。但它打印错误并停止运行。希望你能帮助我。

import os

try:
    for rootDir, subdir, files in os.walk("Z:"):
        for filenames in files:
            if filenames.endswith((".csv")) and not filenames.endswith(("LBL.csv")) and not             
            filenames.endswith(("Code.csv")):
                foundfiles = os.path.join(rootDir, filenames)
                os.remove(os.path.join(rootDir, filenames))
except Exception as e: 
   print(e)
91zkwejq

91zkwejq1#

首先,你可以用函数更好地分割文件名和扩展名。

import os

try:
    for root, subdir, files in os.walk("..."):
        for file in files:
            name, extension = os.path.splitext(file)
            if extension == ".csv" and name != "..." and name != "...":
                try:
                    found_file = os.path.join(root, file)
                    os.remove(found_file)
                except Exception as e:
                    print(e)
except Exception as e: 
   print(e)
j7dteeu8

j7dteeu82#

好的,谢谢你的快速输入。但是你的代码@multimoehre删除了我想保留的2种类型。csv或LBL。csv不是这些文件的全名,它们只是这样结束。所以我和你的代码的混合是解决方案。谢谢。

try:
    for root, subdir, files in os.walk("Z:"):
            for filenames in files:
                if filenames.endswith((".csv")) and not     
                filenames.endswith(("LBL.csv")) and not 
                filenames.endswith(("Code.csv")):
                    try:
                        oundfiles = os.path.join(root, filenames)
                        os.remove(os.path.join(root, filenames))
                    except Exception as e:
                        print(e)
except Exception as e: 
   print(e)

相关问题