我有几个文件夹,每个文件夹包含几个子文件夹,包含5-6个.txt文件,每个文件都有水果(苹果,梨,葡萄等)的列表。然而,一些随机的.txt文件包含“鸡”,必须删除。
我正在尝试写一个程序,它将浏览每个文件夹和子文件夹,删除包含字符串“鸡”的文件,但它似乎不工作,因为某些原因。
以下是我到目前为止所拥有的代码:
import os
DIR = r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\fruits'
for parent, dirnames, filenames in os.walk(DIR):
for fn in filenames:
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, fn))我收到的错误信息如下
File <stdin>, line 4, in <module>
FileNotFoundError: [errno 2] No such file or directory:我也不知道为什么。
任何关于如何让代码顺利运行的建议都是非常感谢的!
发布于 2019-04-11 05:00:28
您有缩进问题。在for循环中使用以下代码
for line in f:
if 'chicken' in line:
found = True
break发布于 2019-04-11 05:40:37
我不确定为什么当你可以直接删除文件的时候,你要打破然后删除。你的代码是正确的,但是结构和缩进是错误的。我希望这能帮助解决你的问题。
import os
root = r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\fruits'
for path, subdirs, files in os.walk(root):
for name in files:
# get file path
file_path = os.path.join(path, name)
# read content of file
with open(file_path) as f:
content = f.readlines()
# delete if it include key word
for line in content:
if "chicken" in line:
os.remove(file_path)
breakhttps://stackoverflow.com/questions/55621231
复制相似问题