当前位置: 代码迷 >> python >> Python Shutil 移动失败:找不到文件
  详细解决方案

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

热度:114   发布时间:2023-07-16 11:12:40.0

我在下面的代码中收到一条错误消息, 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)

您错误地理解了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)