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

问题描述 投票:0回答:2

我在下面的代码上显示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)

[我在下面的代码上看到一个错误,指示FileNotFoundError:[WinError 2]系统找不到指定的文件:'Harry White.txt'->'C:\\ Users \\ johna \\ Desktop \\ z_testingmove \\ Harry White \\ ...

python shutil
2个回答
0
投票

您对shutil.move功能的理解不正确。


0
投票

您对shutil.move功能的理解不正确。

[shutil.move(src, dst)

将文件或目录(src)递归移动到另一个位置(dst)并返回目的地。

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)
© www.soinside.com 2019 - 2024. All rights reserved.