I wrote this piece of code below, but I'm sure it can be done in a more Pythonic way. Only, my knowledge is not that much to be able to figure out a more efficient way.

The DOCX and PDF files are in the same folder.

def compare_text_docx_pdf(path):
    for i in range(0, len(os.listdir(path))):
        if os.listdir(path)[i].upper().endswith('.PDF') and '.' not in os.listdir(path)[i][:7]:
            for j in range(0, len(os.listdir(path))):
                if os.listdir(path)[j].upper().endswith('.DOCX'):
                    if os.listdir(path)[i][:7] == os.listdir(path)[j][:7]:
                            print('PDF:', os.listdir(path)[i][:7])
                            print('DOCX:', os.listdir(path)[j][:7])
                        except Exception as e:

1 Answer 1


If your directory is only containing two types of files, I would do the following way, using splitext function and Counter:

import os
from os.path import splitext
from collections import Counter

def compare_text_docx_pdf(path):
    #List containing all file names + their extension in path directory
    myDir = os.listdir(path)
    #List containing all file names without their extension (see splitext doc)
    l = [splitext(filename)[0] for filename in myDir]
    #Count occurences
    a = dict(Counter(l))
    #Print files name that have same name and different extension
    for k,v in a.items():
        if v > 1:
  • \$\begingroup\$ Note that this solution does not look for .pdf and .docx extensions specifically; it treats all extensions the same way. \$\endgroup\$ Nov 15, 2017 at 0:02
  • \$\begingroup\$ Counter has an items method, no need to convert to dict \$\endgroup\$ Nov 15, 2017 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.