【问题标题】:Python doesn't delete every file/dirPython不会删除每个文件/目录
【发布时间】:2019-12-28 00:04:12
【问题描述】:

我想将“temp”文件夹的内容移动到主文件夹,其中包含例如 2 个文件夹和 1 个文件:

1. Hello
2. World
3. python.exe

temp 文件夹中,我有完全相同的内容。我想先删除main文件夹的内容,然后将temp文件夹的内容移动到main文件夹,因为我删除了所有的文件和文件夹,对吧?

问题是 os.rmdiros.remove 不会删除所有文件...它可能会删除 4 个文件中的 2 个文件和 2 个文件中的 1 个文件夹。我没有收到任何与权限相关的错误,我只得到shutil 错误说目标路径已经存在(因为它没有被os.rmdir() 出于某种原因删除)。:

Traceback (most recent call last):
  File "C:/Users/Test/Desktop/test_folder/ftpdl.py", line 346, in run
    shutil.move(os.getcwd() + "\\temp\\" + f, os.getcwd())
  File "C:\Python\lib\shutil.py", line 564, in move
    raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path 'C:\Users\Test\Desktop\test_folder\Mono' already exists

我的代码如下所示:

dircontents = os.listdir(os.getcwd())
for file in dircontents:
    if file == os.path.isfile(os.getcwd() + "\\" + file):
        if file != 'testfile.py' and file != 'logo.ico' and file != 'settings.xml' and file != 'settings_backup.xml':
            os.remove(os.getcwd() + "\\" + file)
            break
    if file == os.path.isdir(os.getcwd() + "\\" + file):
        if file != 'temp':
            os.rmdir(os.getcwd() + "\\" + file)
            break

newfiles = os.listdir(os.getcwd() + "\\temp")
for f in newfiles:
    shutil.move(os.getcwd() + "\\temp\\" + f, os.getcwd())

预期的结果是主文件夹的所有旧内容都被删除,临时文件夹中的新内容被移动到主文件夹,但它完全不起作用。我会说它部分工作。

【问题讨论】:

  • file == os.path.isfile(os.getcwd() + "\\" + file) 永远不会为真,因为file 永远不会是TrueFalse,但os.path.isfile() 只会返回一个布尔值。
  • 接下来,即使if 测试永远是True,您也使用了break,因此缩短了循环。 dircontents 中的其余文件名永远不会被处理。

标签: python python-3.x file directory shutil


【解决方案1】:

这是不正确的:

if file == os.path.isfile(os.getcwd() + "\\" + file):

isfile() 返回TrueFalse,而不是文件名。您应该只测试调用的结果,而不是将其与文件名进行比较。

也没有必要在前面加上os.getcwd()——相对路径名总是相对于当前目录进行解释。同样,os.listdir() 默认为当前目录。

应该是这样的:

if os.path.isfile(file):

你不应该有break——这会使循环在它删除的第一件事后停止。

并使用elif 进行第二次测试,因为这两种情况是互斥的。

dircontents = os.listdir()
for file in dircontents:
    if os.path.isfile(file) and file not in ['testfile.py', 'logo.ico', 'settings.xml', 'settings_backup.xml']:
        os.remove(file)
    elif os.path.isdir(file) and file != 'temp':
        os.rmdir(file)

newfiles = os.listdir("temp")
for f in newfiles:
    shutil.move("temp\\" + f, os.getcwd())

【讨论】:

  • 嗯,它很管用...我将这部分:elif os.path.isdir(file): if file != 'temp': os.rmdir(file) break 更改为这个,因为我要删除的目录不为空:elif os.path.isdir(file): if file != 'temp': shutil.rmtree(file, ignore_errors=True) break 虽然,它并没有删除所有内容,我甚至不会出现任何错误。
  • 有什么办法吗?
  • break 仍然会结束循环,因此删除目录后不会删除任何内容。
  • 这就是你没有删除所有内容的原因。
  • 谢谢。我完全忘记了。它现在完美运行。
猜你喜欢
  • 2023-01-07
  • 2021-01-22
  • 2014-04-06
  • 2019-02-11
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2020-02-04
  • 2020-09-11
相关资源
最近更新 更多