FileNotFoundError,即使在重命名之前需要通过条件



我正在写一个脚本,应该自动移动和重命名大量的pdf文件。这些文件最初是在一个临时目录中下载的,它们最初下载的路径保存在一个json文件中。文件确实存在于我在脚本中指示的源位置,我甚至使用了相同的变量来通过在尝试重命名之前检查文件是否存在的条件,并且我仍然得到一个FileNotFoundError

我代码:


def distribute(source, title_journal, year_of_issue, volume_and_issue, title): # title_journal, year_of_issue and volume_and_issue are just strings of directory names
root_destination = os.path.join(package_path, "Downloads") # package_path = working directory (os.getcwd()), "Downloads" = parent directory where files will be moved
journal_destination = os.path.join(root_destination, title_journal) 
year_destination = os.path.join(journal_destination, year_of_issue)
file_destination = os.path.join(volume_destination, title)
volume_destination = os.path.join(year_destination, volume_and_issue)
current_path_to_file = source
file_destination = os.path.join(volume_destination, f”{title}.pdf”)
os.rename(current_path_to_file, file_destination)

current_path = Path(dictionary["Download_path"]) # is an absolute path to the file's current location
if current_path.is_file():
distribute(current_path, journal, year, volume, next(iter(dictionary))) 

错误示例(编辑以显示脚本中的变量):

FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/Documents/run1/Downloads/Temporary_folder/09567976211043428.pdf' -> '/Users/me/Documents/Downloads/journal_title/year_of_issue/volume_and_issue/new_file_name'

假设/Users/me/Documents/Downloads已经存在,该错误告诉您该目录中的一个或多个目录journal_title/year_of_issue/volume_and_issue不存在,并且不会隐式创建

通常的解决方案是用exist_ok=True调用os.makedirs以确保目标目录结构存在。

file_destination = os.path.join(volume_destination, f"{title}.pdf")
os.makedirs(volume_destination, exist_ok=True) # <------
os.rename(current_path_to_file, file_destination)

顺便说一下,我还必须改变花括号">

相关内容

  • 没有找到相关文章

最新更新