我正在制作一个脚本来生成文件夹并使用 shutil 在 Python on Windows 10 中将图像移动到它们,但它抛出以下错误

I'm making a script to generate folders and move images to them in Python on Windows 10 using shutil, but it's throwing the errors below

我遇到了这些错误:

Traceback (most recent call last):
  File "file_mover.py", line 41, in <module>
    shutil.copy(f, os.path.join(path_to_export_two, Path("/image/")))
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\shutil.py", line 245, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: '8ballshake1@8x.png'

执行这段代码时:

# Making the substrings is more difficult then anticipated prolly just use Java tbh
# LOWERCASE, LOWERCASE THE FOLDERS
import shutil
import os
from pathlib import Path

assets_path = Path("/Users/Jackson Clark/Desktop/uploads")
export_path = Path("/Users/Jackson Clark/Desktop/uploads")

source = os.listdir(assets_path)

"""
NOTE: Filters.js is the important file
The logic:
    - Go through each file in the assets_path directory
    - Rename the files to start with RoCode (this could be a seperate script)
    - Create a new directory with the first four characters of the files name
    - Create two sub directories with the names 'image' and 'thumb'
    - Copy the file to both the 'image' and 'thumb' directories
    That should be all, but who knows tbh
"""
"""
Good links:
    https://www.pythonforbeginners.com/os/python-the-shutil-module
    https://stackabuse.com/creating-and-deleting-directories-with-python/
"""

for f in source:
    f_string = str(f)
    folder_one_name = f_string[0:2]
    folder_two_name = f_string[2:4]

    path_to_export_one = os.path.join(export_path, folder_one_name)
    path_to_export_two = os.path.join(export_path, folder_one_name, folder_two_name)

    os.mkdir(path_to_export_one)
    os.mkdir(path_to_export_two)
    os.mkdir(os.path.join(path_to_export_two, Path("/image/")))
    os.mkdir(os.path.join(path_to_export_two, Path("/thumb/")))

    shutil.copy(f, os.path.join(path_to_export_two, Path("/image/")))
    shutil.copy(f, os.path.join(path_to_export_two, Path("/thumb/")))

我只需要生成两个文件夹的代码,第一个被命名为脚本正在读取的文件的前两个字符,第二个文件夹(它是第一个文件夹的子文件夹)被命名为第三个和脚本正在读取的文件名的第 4 个字符。唉,我遇到了上面的错误。

去掉 Path 中的前导斜杠。这些导致路径被截断:

>>> print(os.path.join("some_folder", Path("/image/")))
\image
>>> print(os.path.join("some_folder", Path("image")))
some_folder\image

os.path.join documentation的相关语句如下:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

/image/ 中的前导斜线导致此路径组件变为绝对路径,因此之前的组件(在我的例子中,只是 "some_folder")被丢弃。

此外,我不明白你为什么要从字符串创建 Path,而你可以直接使用字符串:

>>> print(os.path.join("some_folder", "image"))
some_folder\image