Sunday 10th January 2021: Python Weekly Challenge

Today I came across Weekly Python ...

Python programming projects sent weekly to help you practice and perfect your programming skills while building your project portfolio.

There's a ton of such like out there and all vying for our attention. I like the understated and minimal style of this one. The first challenge was set just a week ago on. Listing all files in a directory.

Happy to have completed the beginner project. Went on and practised more by completing the beginner stretched goal. So far I have learned about using Pythons inbuilt os and argparse modules.

There's more to be rinsed from the challenge with the inclusion of intermediate and advanced projects and stretched goals.

For now though...

import argparse
import os

# Beginner project: Create a python script that will print the names of every file in the directory you run it from in alphabetical order. Only print the names of files and not include folders in the returned list. Make sure the list is printed with one file per line of output. 
# Beginner stretch Goal: Add a command-line argument to also include the names of every folder in the current working directory.

path = os.getcwd()
file_list = []

# block executed if no command line argument entered. Just files from the CWD are sent to Stdout.
for files in os.listdir(path):
    if os.path.isfile(os.path.join(path, files)):
        file_list.append(files)
file_list.sort()
for file in file_list:
    # to exclude hidden files
    if file[0] == '.':
        continue
    print(file)

# block executed if command line argument entered. Files and directories from the CWD are sent to Stdout.
parser = argparse.ArgumentParser()
parser.add_argument("--dir", help="Include the names of every directory in the current working directory.")
args = parser.parse_args()

if args.dir:
    dl = os.listdir(os.getcwd())
    dl.sort()
    for i in dl:
        # to exclude hidden files
        if i[0] == '.':
            continue
        print(i)


You'll only receive email when they publish something new.

More from Alex Turner