【问题标题】:Walk directories and remove file extensions遍历目录并删除文件扩展名
【发布时间】:2021-12-28 22:15:39
【问题描述】:

我正在尝试从网络 PC 上的用户文件夹中删除所有 Outlook .ost 和 .nst 文件,并试图让它将删除的文件写入 CSV 文件。

我能够让它找到目录中的所有文件并将其写入 CSV 文件,但是当我尝试使用 os.remove 删除文件时,它似乎没有运行,我对其进行了哈希处理暂时。

我在 try 和 except 中添加了跳过正在使用的文件。

import os
import sys

sys.stdout = open("output_file.csv", "w")
try:
    for rootDir, subdir, files in os.walk("//network_pc_name/c$/Users"):
        for filenames in files:
            if filenames.endswith((".nst",".ost")):
                foundfiles = os.path.join(rootDir, filenames)
                #os.remove(os.path.join(rootDir, filenames))
                print(foundfiles)
except:
    pass
sys.stdout.close()

我按照建议对脚本进行了一些更改,它似乎运行得更快了,但是,我似乎无法弄清楚如何忽略正在使用的文件。

我将文件扩展名切换为 .xlsx 和 .txt 文件,以模拟打开的 .xlsx 文件接收权限错误,并查看脚本是否会继续运行并删除 .txt 文件。

我收到以下错误: PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:'//DESKTOP-HRLS19N/c$/globtest\Book1.xlsx

import glob
import os

files = [i for i in glob.glob("//DESKTOP-HRLS19N/c$/globtest/**", recursive = True) if i.endswith((".xlsx",".txt"))]

[os.remove(f) for f in files]
with open("output_file.csv", "w") as f:
    f.writelines("\n".join(files))

【问题讨论】:

  • 您说“它似乎没有运行” - 您是否收到错误消息、脚本是否挂起、甚至拒绝启动?请分享任何信息或行为。

标签: python glob os.walk


【解决方案1】:

根据我的经验,glob 要容易得多:

print([i for i in glob.glob("//network_pc_name/c$/Users/**", recursive=True) if i.endswith((".nst", ".ost"))])

假设打印出您期望的文件:

files = [i for i in glob.glob("//network_pc_name/c$/Users/**", recursive=True) if i.endswith((".nst", ".ost"))]
removed_files = []
for file in files:
    try:
        size = os.path.getsize(file)
        os.remove(file)
        removed_files.append(file + " Bytes: " + size)
    except Exception as e:
        print("Could not remove file: " + file)
with open("output_file.csv", "w") as f:
    f.writelines("\n".join(removed_files))

【讨论】:

  • 我尝试了上面的代码,它奏效了,但由于某种原因,我无法尝试,除非通过忽略正在使用的文件,我收到以下错误:[ WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:
  • 查看我编辑的答案^。也是best practice to not use try: except: pass
  • 终于有机会测试它,它运行良好,由于它通过网络搜索的文件夹数量有点慢,但它可以工作,最后一件事,任何机会你知道我可以将文件的大小添加到输出中。
  • removed_files.append(file) -> removed_files.append(file + " Bytes: " + os.path.getsize(file))
  • 我尝试了获取文件大小的代码,但它似乎不起作用,removed_files.append(file + " Bytes: " + os.path.getsize(file)) 它只给出了正常输出,不添加“字节:”或 os.path.getsize(file)