OpenSesame
Rapunzel Code Editor
DataMatrix
Support forum
Python Tutorials
MindProbe
Python videos

Modules: Exercises and Solutions

Files and folders

Exercise

Use the os and os.path modules to list the contents of your Downloads folder, and indicate for each item whether it's a file or a folder.

Solution

import os

dirname = '/home/sebastiaan/Downloads'
for basename in os.listdir(dirname):
  path = os.path.join(dirname, basename)
  if os.path.isdir(path):
    print('folder: {0}'.format(path))
  else:
    print('file:   {0}'.format(path))

Output:

file:   /home/sebastiaan/Downloads/revised_ms.docx
folder: /home/sebastiaan/Downloads/.config
file:   /home/sebastiaan/Downloads/34-278-1-PB.pdf

You're done with this section!

Continue with Modules >>