'Deleting images in a list
I've created a simple converter from images to pdf in pyhon. The idea was that after creating the pdf with all the images, the images get deleted. Here's the code:
from PIL import Image
import os
# from os.path import isfile, join
img_path = input('Entr the path with the images: ')
list = os.listdir(img_path)
# list = [file for file in os.listdir(path) if isfile(join(path, file))]
images = [
Image.open(img_path + f)
for f in list
]
print('Images used to create the pdf:\n' +'--> '+str(list))
print('The PDF will be saved here:\n' +'--> '+str(img_path))
pdf_path = img_path + "myPDF.pdf"
images[0].save(
pdf_path, "PDF" , resolution=100.0, save_all=True, append_images=images[1:]
)
# not working part
print("Deleting images...\n")
for i in range(len(list)):
if '.JPG' or '.NEF' in list[i]:
os.remove(list[i])
print(list[i]+' deleted')
print('--> PDF creato e salvato!\n Check: '+img_path)
The pdf is created correctly, however when the code is supposed to delete the images it gives me this error:
Traceback (most recent call last):
File "c:\vscode\PYTHON\imagestopdf.py", line 26, in <module>
os.remove(list[i])
FileNotFoundError: [WinError 2] Impossible to find the file specified: 'photo.JPG'
I can't understand where I did wrong. Anyone has any idea?
Solution 1:[1]
Use os.path.join(img_path, list[i]) inside os.remove
I would highly recommend you use pathlib library instead of os.path
Instead of using + to join the path and file name use os.path.join
For pathlib simply
import pathlib
img_path = pathlib.Path(img_path)
# to join path with file
img_path / "image.png"
# its that easy and this handles different file systems
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stalin Thomas |
