I often use Word to create documents, but After promoting paperless offices and introducing groupware, Start with a voice from your boss saying, "Let's convert Word files to PDF and manage documents centrally !!"
The battle with countless ".doc" and ".docx" that I do not know how many begins ... Of course, no one in the company can use python, so I tried it implicitly.
import win32com.client import os #Install the required modules wd = win32com.client.Dispatch('Word.Application') #Declaration to "manipulate Word" documents_path = 'C:/test/' word_list =  #Set the path of the folder where the files are stored #word_file_Empty list to store name(word_list)Create for word_file_name in os.listdir(documents_path): if os.path.isfile(os.path.join(documents_path, word_file_name)): word_list.append(word_file_name) for i in range(0,len(word_list)): try: word_file = wd.Documents.Open(documents_path + '/' + word_list[i]) base_name, ext = os.path.splitext(word_list[i]) #base_name,By ext, the extension is entered in ext and the file name is base._Stored in name word_file.SaveAs2(FileName = documents_path + base_name + '.pdf', FileFormat = 17) #Specify file name, format(17 is PDF[https://docs.microsoft.com/ja-JP/office/vba/api/word.wdsaveformat])The set except Exception as e: print(e) #Store exception handling other than try in e, and display if there is finally: word_file.Close() print('complete')
After a lot of trial and error, I got the above code. I think it's quite redundant because it's a beginner.
documents_path is for posting this time, so it is set as test, When using it, specify the path of the folder where the Word file is stored.
・ The for statement is included twice, and I originally wanted to combine it into one. In the with statement, pywin32 did not work well, so it is necessary to take improvement measures in the future.
-Try with modules other than pywin32.
・ Clean up redundant parts.
I was originally interested in python, and I've been working on it, but it was the first time I actually completed something. It may be a bad idea for professionals, but I would like to get used to writing even the smallest code. Since there are many parts that can be improved in-house by using automation, we will steadily post the results of our efforts to Qiita as a memorandum.
We would appreciate any improvements or advice! Thank you.