python - 如果目录中包含字符串 [],则删除目录中的所有文件
问题描述
我有一个包含 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'
解决方案
我看到了其他问题,但让我来解决您的问题:
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))
推荐阅读
- javascript - 在 OpenUI5-App 中导入 Leaflet-Library
- azure-devops - 注册到环境时标记资源
- react-apollo - 如何使用 reactjs @apollo/client v3 获取所有缓存数据
- android - 是否可以在 Windows 10 中安装 IOS 模拟器?
- forms - 防止 Powershell GUI 关闭
- javascript - 对 NaN 感到困惑 - HTML CANVAS JS
- laravel - 在 laravel 'created' 事件中获取新创建的 id
- vue.js - Vue和Vuetify中未出现错误消息
- java - Concat Flux 及其计数(或另一个 reduce 函数)
- java - 使用 google cloud run 部署 pub/sub spring 应用程序