首页 > 解决方案 > 如果目录中包含字符串 [],则删除目录中的所有文件

问题描述

我有一个包含 5 个 .txt 文件的文件夹:

100240042.txt
102042044.txt
016904962.txt
410940329.txt
430594264.txt

一种包含不同类型的水果(例如苹果、香蕉、橙子等)。但是,其他的都包含“鸡”。这些必须删除,只留下水果列表。

到目前为止,我已经尝试了 4 种不同的解决方案

尝试 0

import os
for filename in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    f = open(filename)
    for line in filename:
        if 'chicken' in line:
            found=true
            os.remove(filename)
    f.close()

尝试 1

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    open(file, 'r')
    f.read()
    find('chicken')
    os.remove()
    f.close()

尝试 2

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    open(file, 'r')
    f.read()
    find('chicken')
    os.remove()
    f.close()

尝试 3

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    if 'chicken' in open(file).read():
    os.remove(file)
    f.close()

我认为这是一个相对简单的问题,但我不断收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '100240042.txt'

标签: python

解决方案


我看到了其他问题,但让我来解决您的问题:

os.remove(filename)

这是在当前目录执行的。通常是您运行程序的目录。但是,如果您尝试rm filename在 shell 上运行命令,您也会看到错误,因为该文件实际上位于另一个目录中。你想要做的是:

open(os.path.join(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits', filename))

并且:

os.remove(os.path.join(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits', filename))

因此,您的代码应如下所示:

DIR = r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'
for filename in os.listdir(DIR):
    found = False
    with open(os.path.join(DIR, filename)) as f:
        for line in f:
            if 'chicken' in line:
                found = True
                break
    if found:
        os.remove(os.path.join(DIR, filename))

推荐阅读