How to create methods in Python

1 min

Python will allow you to create your own methods.

What I mean by methods are pieces of code that you can re-use multiple times.

You will define it once within your main script and will be able run it multiple times, with different parameters.

Here is an example

Here is an example of a method that I use quite often.

def get_csv_in_folder(path):
    """Return the list of csv files in a specific folder
    	path (string) : Path to the folder of interest
    	(list) : all the csv files contained in given folder path
    import os # We can import libraries within the scope of the method

    # We uses the list comprehension capability of python to create
    # The list of csv files in a folder. You can do the same in a loop
    # This can be read as the following
    # Give me every object in the folder (path) where .csv is in the name
    folder_list = [each for each in os.listdir(path) if ".csv" in each]

    return folder_list
Retrieving the list of csv files in a folder

Passing parameters to the method

In order for the method to process information, a good way to send them data is through the use of parameters.

Here is an example with three parameters:

def my_method(parameter1, parameter2, parameter3):
	print(f"param1 : {parameter1}\nparam2 : {parameter2}\nparam3:\n {parameter3}")
Example of method that prints out three parameters

A real life situation

So imagine you are working on a project that requires you to list the csv files contained in a specific folder. (e.g. sales of your e-commerce that has been splitted in files per month) see below.

└── data
      ├── january.csv
      └── february.csv
print(get_csv_in_folder("./data")) # This will give you the list of csv files contained in the data folder.

Here you are !

You can now reuse this method in other projects without running into problems.