【发布时间】:2019-12-28 00:04:12
【问题描述】:
我想将“temp”文件夹的内容移动到主文件夹,其中包含例如 2 个文件夹和 1 个文件:
1. Hello
2. World
3. python.exe
在temp 文件夹中,我有完全相同的内容。我想先删除main文件夹的内容,然后将temp文件夹的内容移动到main文件夹,因为我删除了所有的文件和文件夹,对吧?
问题是 os.rmdir 和 os.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永远不会是True或False,但os.path.isfile()只会返回一个布尔值。 -
接下来,即使
if测试永远是True,您也使用了break,因此缩短了循环。dircontents中的其余文件名永远不会被处理。
标签: python python-3.x file directory shutil