0

I have a simple python script to convert files to PDF. It has another function I made to merge them to one PDF file imported at the top. However, every time I run the convert script it runs the merge script as well even when I don't call the F_merge. The convert script is below. Why/where is it calling F_Merge?

# Converts files  to PDF

from PIL import Image
import os,glob2,re
from PDF_Merge_Script import F_Merge

def Converter(filename):
    im = Image.open(filename)
    if im.mode == "RGBA":
        im = im.convert("RGB")
    if filename[-4:-1] == "jpe":
        new_filename = filename[:-4]+'pdf'
        if not os.path.exists(new_filename):
        im.save(new_filename,"PDF",resolution=100.0)
else:
    new_filename = filename[:-3]+'pdf'
    if not os.path.exists(new_filename):
        im.save(new_filename,"PDF",resolution=100.0)

PNG_files = glob2.glob("*.PNG")
JPEG_files = glob2.glob("*.jpeg")
JPG_files = glob2.glob("*.JPG")
Txt_files = glob2.glob("*.txt")

print(Txt_files)
print(PNG_files)
print(JPEG_files)
print(JPG_files)

This is my output. No error. The printed statement is from a conditional in my merge function.

Intially, No .pdf files in current directory or only one .pdf exists in directory

['file1.txt']

[]

[]

[]

Here is the Merge Script

#Merges all .pdf files in the current directory where this scipt is saved

 from PyPDF2 import PdfFileMerger
 import os,glob2,re

 def  F_Merge(path):
  pdf_files = glob2.glob("*.pdf")
  if len(pdf_files) <= 1:
    print("Intially, No .pdf files in current directory or only one .pdf 
    exists in directory")
 else:
    merger = PdfFileMerger()
    for files in pdf_files:
        merger.append(path+files)
    if not os.path.exists(path+'merged.pdf'):
        merger.write(path+'merged.pdf')
    merger.close()
    print('\n'.join(pdf_files)+"\nmerged to file named merged.pdf in current folder")


path = re.sub(r'\\',r'/',os.getcwd()[2:])+'/'
F_Merge(path)
John
  • 41
  • 6
  • What's the output/traceback? – vmonteco Dec 12 '17 at 20:08
  • @vmonteco Just added my output. No errors. – John Dec 12 '17 at 20:12
  • 2
    You need to post the contents of `PDF_Merge_Script.py` in order for anyone here to know what's going on, but luckily for you my psychic powers are telling me you need to read ["What does `if __name__ == “__main__”:` do?"](https://stackoverflow.com/q/419163/744178). – jwodder Dec 12 '17 at 20:15
  • Added the output and other file – John Dec 12 '17 at 20:20
  • 1
    Looks like @jwodder was correct, your `F_Merge` function is automatically executed when you import something from PDF_Merge_Script.py – rickdenhaan Dec 12 '17 at 20:22
  • Yeah, all I needed was if__name__ == '__main__' in my merge script, thanks! – John Dec 12 '17 at 21:16

0 Answers0