Repository: yt-dlp/yt-dlp

Issue:
"FileNotFoundError: [Errno 2] No such file or directory" appears when downloading a YouTube playlist with thumbnails
### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting that yt-dlp is broken on a **supported** site
- [X] I've verified that I'm running yt-dlp version **2023.09.24** ([update instructions](https://github.com/yt-dlp/yt-dlp#update)) or later (specify commit)
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)
- [X] I've read about [sharing account credentials](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#are-you-willing-to-share-account-details-if-needed) and I'm willing to share it if required

### Region

Indonesia

### Provide a description that is worded well enough to be understood

When downloading YouTube playlist thumbnails, a FileNotFoundError message appears and the download process stops. This error does not occur if one of the following conditions are met:
1. The target output path folder is created manually first, not relying on Yt-dlp to create it.
2. Without using the --write-thumbnail parameter when downloading a YouTube playlist.
3. Downgrade yt-dlp to version 2023.06.22

### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [ ] If using API, add `'verbose': True` to `YoutubeDL` params instead
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
[debug] Command-line config: ['-vU', '--yes-playlist', 'https://www.youtube.com/watch?v=wNoVFDDSqB0&list=PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR&pp=iAQB', '-i', '-f', 'bv*[height=1080][ext=mp4]+ba[ext=m4a]/bv*[height<=1080][ext=mp4]+ba[ext=m4a]/b[height<=1080][ext=mp4]', '--write-subs', '--sub-langs', 'en,id,-live_chat', '--convert-subs', 'srt', '--write-thumbnail', '--abort-on-unavailable-fragment', '--no-mtime', '--add-metadata', '--extractor-args', 'youtube:player-client=web', '--downloader', 'aria2c', '--downloader-args', 'aria2c:-x 16 -k 1M --max-overall-download-limit=6451K --auto-file-renaming', '-r', '6.3M', '--cookies-from-browser', 'brave', '--progress', '--progress-template', 'download-title:(progress.eta)s', '-o', 'D:\\Users\\Supervisor\\Downloads\\Video\\%(channel)s\\%(playlist_title)s\\%(title)s (%(upload_date)s).%(ext)s']
Extracting cookies from brave
[debug] Extracting cookies from: "C:\Users\Supervisor\AppData\Local\BraveSoftware\Brave-Browser\User Data\Default\Network\Cookies"
[debug] Found local state file at "C:\Users\Supervisor\AppData\Local\BraveSoftware\Brave-Browser\User Data\Local State"
Extracted 2705 cookies from brave
[debug] cookie version breakdown: {'v10': 2705, 'other': 0, 'unencrypted': 0}
[debug] Encodings: locale cp1252, fs utf-8, pref cp1252, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version stable@2023.09.24 [088add956] (win_exe)
[debug] Python 3.8.10 (CPython AMD64 64bit) - Windows-10-10.0.19045-SP0 (OpenSSL 1.1.1k  25 Mar 2021)
[debug] exe versions: ffmpeg n6.0-34-g3d5edb89e7-20230924 (setts), ffprobe n6.0-34-g3d5edb89e7-20230924, phantomjs 2.1.1
[debug] Optional libraries: Cryptodome-3.19.0, brotli-1.1.0, certifi-2023.07.22, mutagen-1.47.0, sqlite3-3.35.5, websockets-11.0.3
[debug] Proxy map: {}
[debug] Loaded 1886 extractors
[debug] Fetching release info: https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest
Available version: stable@2023.09.24, Current version: stable@2023.09.24
Current Build Hash: 125465ac4416bcd4bf1632b899630ceecc08b341e83fdf10bd34700c58ea5152
yt-dlp is up to date (stable@2023.09.24)
[youtube:tab] Extracting URL: https://www.youtube.com/watch?v=wNoVFDDSqB0&list=PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR&pp=iAQB
[youtube:tab] Downloading playlist PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR - add --no-playlist to download just the video wNoVFDDSqB0
[youtube:tab] PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR: Downloading webpage
[youtube:tab] Extracting URL: https://www.youtube.com/playlist?list=PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR
[youtube:tab] PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR: Downloading webpage
[debug] [youtube:tab] Extracted SAPISID cookie
[youtube:tab] PLSMVvri4yXjiimb1X3phH4MQAAfeZUgBR: Redownloading playlist API JSON with unavailable videos
[download] Downloading playlist: Gel Pens
[info] Downloading playlist thumbnail 3 ...
[info] Writing playlist thumbnail 3 to: D:\Users\Supervisor\Downloads\Video\JetPens\Gel Pens\Gel Pens (NA).jpg
ERROR: [Errno 2] No such file or directory: 'D:\\Redacted\\Video\\JetPens\\Gel Pens\\Gel Pens (NA).jpg'
Traceback (most recent call last):
  File "yt_dlp\YoutubeDL.py", line 1567, in wrapper
  File "yt_dlp\YoutubeDL.py", line 1723, in __extract_info
  File "yt_dlp\YoutubeDL.py", line 1852, in process_ie_result
  File "yt_dlp\YoutubeDL.py", line 1950, in __process_playlist
  File "yt_dlp\YoutubeDL.py", line 4257, in _write_thumbnails
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\Users\\Supervisor\\Downloads\\Video\\JetPens\\Gel Pens\\Gel Pens (NA).jpg'
```



Discussion:

Resolving patch:
diff --git a/yt_dlp/YoutubeDL.py b/yt_dlp/YoutubeDL.py
--- a/yt_dlp/YoutubeDL.py
+++ b/yt_dlp/YoutubeDL.py
@@ -4229,7 +4229,7 @@ def _write_subtitles(self, info_dict, filename):
         return ret
 
     def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
-        ''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename) '''
+        ''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error '''
         write_all = self.params.get('write_all_thumbnails', False)
         thumbnails, ret = [], []
         if write_all or self.params.get('writethumbnail', False):
@@ -4245,6 +4245,9 @@ def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None
             self.write_debug(f'Skipping writing {label} thumbnail')
             return ret
 
+        if not self._ensure_dir_exists(filename):
+            return None
+
         for idx, t in list(enumerate(thumbnails))[::-1]:
             thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
             thumb_display_id = f'{label} thumbnail {t["id"]}'


Test patch: