Python Shutil移动失败:未找到文件

2024-10-03 21:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面的代码中得到一个错误,上面写着:FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Harry White.txt' -> 'C:\\Users\\johna\\Desktop\\z_testingmove\\Harry White\\Harry White.txt'

有人能帮我吗

import shutil
import os, sys

source = 'C:\\Users\\johna\\Desktop\\z_testingmove'
dest1 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\Harry White'
dest2 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\John Smith'
dest3 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\Judy Jones'

files = os.listdir(source)

for f in files:
    if f == "Harry White.txt":
        shutil.move(f, dest1)
    elif f == "John Smith.txt":
        shutil.move(f, dest2)
    elif f == "Judy Jones.txt":
        shutil.move(f, dest3)

Tags: importtxtsourcemoveosjohnuserswhite
1条回答
网友
1楼 · 发布于 2024-10-03 21:26:11

您错误地理解了shutil.move函数

The shutil.move(src, dst)

Recursively move a file or directory (src) to another location (dst) and return the destination.

文件或目录的srcdst必须是full path

您必须更改代码,请尝试以下操作:

import shutil
import os, sys

source = 'C:\\Users\\johna\\Desktop\\z_testingmove'
dest1 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\Harry White'
dest2 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\John Smith'
dest3 = 'C:\\Users\\johna\\Desktop\\z_testingmove\\Judy Jones'

files = os.listdir(source)
for filename in files:
    sourcepath = os.path.join(source, filename)
    if filename == "Harry White.txt":
        destpath = os.path.join(dest1, filename)
        shutil.move(sourcepath, destpath)
    elif filename == "John Smith.txt":
        destpath = os.path.join(dest2, filename)
        shutil.move(sourcepath, destpath)
    elif filename == "Judy Jones.txt":
        destpath = os.path.join(dest3, filename)
        shutil.move(sourcepath, destpath)

相关问题 更多 >