-1

I started learning Python a couple weeks ago so I could make this project that saves all the images on multiple webpages. Everything works smoothly except the last lines, I get an error that says:

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'

Here is the code:

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)

I've searched on google for a solution but can't seem to find anything fitting my problem.

  • 1
    You can't create a folder while opening a file. You have to do it separately before – Tomerikoo Jan 23 '22 at 18:59
  • Does this answer your question? [Python3.4: Opening file with mode 'w' still gives me FileNotFound error (duplicate)](https://stackoverflow.com/q/32024460/6045800) – Tomerikoo Jan 23 '22 at 19:02
  • In your own words, where you have `filename = "page" + img_link[img_link.rfind("/"):]` and then `with open(filename, "wb") as file:`, *what directory* do you expect that to operate in? Why? (Do you know what a *current working directory* is?) – Karl Knechtel Jan 23 '22 at 19:04
  • Does this answer your question? [Python create directory error Cannot create a file when that file already exists](https://stackoverflow.com/q/65618858/6045800) – Tomerikoo Jan 23 '22 at 19:06

1 Answers1

0

The explanation is in the error :

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

With no more details, I would think that the directory page/ doesn't exist. Can you check this ?

the open() will create the file if it doesn't exist but not the parent directories.

If this is the problem, you can automatically create it like this:

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