I have the following code that loops through all the images with any extension in multiple folders then to convert those images to pdf I am stuck at the last line of saving the pdf file
from PIL import Image
import os
path = 'MAIN'
ext = ['.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff']
for root, dirs, files in os.walk(path):
for file in files:
if(file.endswith(tuple(ext))):
sFilePath = os.path.join(root,file)
print(sFilePath.split('.')[0])
img = Image.open(sFilePath)
img = img.convert('RGB')
img.save(os.path.join(sFilePath.split('.')[0], '.pdf'))
Another point I need to add is to delete the image file after converting it to pdf
CodePudding user response:
You can do it by using the os.path.splitext()
function to get base part of the image's filename, and then combine that plus the .pdf
extension you want using os.path.join()
. (Note that converting it to RGB
is not the same as converting it to PDF format.)
from PIL import Image
import os
path = './'
ext = ['.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff']
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(tuple(ext)):
src_image_path = os.path.join(root, file)
base_name = os.path.splitext(file)[0]
img = Image.open(src_image_path)
img = img.convert('RGB')
img.save(os.path.join(root, base_name '.pdf'))