【问题标题】:Getting error after attempting to save file in python尝试在 python 中保存文件后出现错误
【发布时间】:2022-01-24 03:11:28
【问题描述】:

几周前我开始学习 Python,所以我可以制作这个项目,将所有图像保存在多个网页上。除了最后几行外,一切正常,我收到一条错误消息:

File "/Users/hitchhiker/Desktop/manga_yoinker/main.py", line 36, in <module> with open(filename, "wb") as file: FileNotFoundError: [Errno 2] No such file or directory: 'page/cropped-Jujutsu_kaisen-324x324-1.png'

代码如下:

import os
import requests
from bs4 import BeautifulSoup
import shutil

link = "https://kaisenscans.com/chapter/jujutsu-kaisen-chapter-"

main_dir = os.path.join("/Volumes/flash", "main_folder")
os.mkdir(main_dir)

for chapter_number in range(1, 2):
    chapter = link + str(chapter_number)
    page = requests.get(chapter)
    chname = "chapter"+str(chapter_number)

current_dir = "/Users/hitchhiker/Desktop/manga_yoinker/" + chname
destination = "/Volumes/flash/main_folder"

dire = os.mkdir(chname)

shutil.move(current_dir, main_dir)

soup = BeautifulSoup(page.content, "html.parser")
imgs = soup.find_all("img")


for img in imgs:
    img_link = img.attrs.get("src")
    image = requests.get(img_link).content
    filename = "page" + img_link[img_link.rfind("/"):]

    with open(filename, "wb") as file:
        file.write(image)

我在谷歌上搜索了解决方案,但似乎找不到任何适合我的问题。

【问题讨论】:

标签: python


【解决方案1】:

解释在错误中:

FileNotFoundError: [Errno 2] No such file or directory: 'page/cropped-Jujutsu_kaisen-324x324-1.png'

没有更多细节,我认为目录page/ 不存在。你能检查一下吗?

open() 将创建 文件,如果它不存在但不存在父目录。

如果这是问题所在,您可以像这样自动创建它:

dir = './page/'
os.makedirs(dir, exist_ok=True)
# Equivalent to :
# if (not os.path.isdir(dir)):
#    os.mkdir(dir)

【讨论】:

猜你喜欢
  • 2014-07-07
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
相关资源
最近更新 更多