在 os.walk() for 循环中使用 os.remove() 返回 FileNotFoundError

2024-01-27

我在 Anaconda 命令提示符中使用 Python 3.6.4。

我有一个使用的函数os.walk()循环遍历根目录中的所有可用文件。

我的代码是:

def apply_to_files(pattern, base='.') :
    regex = re.compile(pattern)
    matches = []
    completed = ''
    for root, dirs, files in os.walk(base):
        for f in files:
            if regex.match(f):
                os.remove(f)

这会触发一个FileNotFoundError具体来说:

FileNotFoundError: [WinError 2] 系统找不到该文件 指定:'c.html'

我将该函数称为:

apply_to_files('c.*', 'C')

我运行该函数的目录具有以下结构:

root
 -C
  -c.html
  -c.txt
  -c.php
 -B
 -D

当我更换时os.remove(f) with print(f)它会按照您的预期返回所有文件。我在这里缺少什么?


The files变量仅包含文件名。当尝试操作文件时,您必须添加完整路径:

for root, dirs, files in os.walk(base):
    for f in files:
        if regex.match(f):
            os.remove(os.path.join(root, f))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 os.walk() for 循环中使用 os.remove() 返回 FileNotFoundError 的相关文章

随机推荐