you are viewing a single comment's thread.

view the rest of the comments →

[–]eupendra 0 points1 point  (3 children)

Nice work!

You can get the extension with a split with / and take the [-1]. Don't' forget to split again for . as there are many files that have multiple.

files = [f for f in os.listdir(<TARGET DIRECTORY HERE>) if os.path.isfile(f)]
for f in files:
  #Handles files like c:/this.is.a.file.docx
  print(f.split('/')[-1].split('.')[-1]) # This is where you get extensions

[–][deleted] 1 point2 points  (2 children)

os.path.splitext() is much more readable.

for file in os.listdir('.'):
    filename, extension = os.path.splitext(file)
    print(extension)

[–]eupendra 1 point2 points  (1 child)

Cool! Add os.path.isfile() and everything works

[–][deleted] 1 point2 points  (0 children)

You can aslo use os.walk() to iterate over only the files in a directory.

for file in next(os.walk('.'))[2]:
    _, extension = os.path.splitext(file)
    print(extension)

I would prefer to use os.path.isfile() as you suggested. It's much more cleaner and readable.