读取文件名时如何修复文件移动脚本中的FileNotFoundError?

时间:2019-05-09 23:02:33

标签: python python-3.x shutil pathlib

我的Python脚本读取文件的前两个字符,创建一个名为前两个字符的文件夹,然后创建一个名为第3个和第4个字符的子文件夹。然后,它将文件复制到子文件夹的两个子文件夹,分别称为image和thumb。但是,即使它正确读取了文件名,当我尝试使用FileNotFoundError时,它也会引发shutil.copy()

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)

    try: 
        os.mkdir(path_to_export_one)
        os.mkdir(path_to_export_two)
        os.mkdir(os.path.join(path_to_export_two, "image"))
        os.mkdir(os.path.join(path_to_export_two, "thumb"))
        shutil.copy(f, os.path.join(path_to_export_two, "image"))
        shutil.copy(f, os.path.join(path_to_export_two, "thumb"))
    except FileExistsError as err:
        try:
            shutil.copy(f, os.path.join(path_to_export_two, "image"))
            shutil.copy(f, os.path.join(path_to_export_two, "thumb"))
        except FileNotFoundError as err:
            print("FileNotFoundError2 on " + f + " file")
    except FileNotFoundError as err:
        print("FileNotFoundError1 on " + f + " file")

1 个答案:

答案 0 :(得分:0)

您使用的f是一个简单的字符串,例如"readme.txt"。这是因为os.listdir()返回给定目录的条目列表,每个条目只是此目录中中的名称(不是完整路径)。您的脚本可能不在此目录中运行,因此无法访问readme.txt

我建议仅在路径f之前添加。

顺便说一句,Path中的pathlib个对象知道运算符/,因此您可以像这样更易读的方式编写代码:

path_to_export_one = export_path / folder_one_name
path_to_export_two = path_to_export_one / folder_two_name
...
f_path = assets_path / f
...
shutil.copy(f_path, path_to_export_two / 'image')