How to Delete a File using Python

The ‘os‘ module can be used to delete a file in Python: Copy import os file_path = r”Path where the file is stored\file_name.file_extension” os.remove(file_path) Example of Deleting a File using Python (1) Let’s suppose that a file called ‘Products‘ is stored in a ‘Test‘ folder, where the full file path is: C:\Users\Ron\Desktop\Test\Products.csv (2) To delete … Read more

Check if a Substring Exists in a String in Python

Here are 2 ways to check if a substring exists in a string in Python: (1) Using the “in” keyword: Copy my_string = “This is an example of a string” my_substring = “example” if my_substring in my_string: print(“Substring found”) else: print(“Substring not found”) The result: (2) Using the “find()” method: Copy my_string = “This is … Read more

Use Python to get the File Paths within a Folder

Here are 3 ways to get the file paths that match specific patterns within a folder: (1) Fetch all CSV files within the specified folder Copy import glob folder_path = r”C:\Users\Ron\Desktop\Test” csv_files = glob.glob(folder_path + r”\*.csv”) print(csv_files) Where: The result is a list containing the full paths of 3 CSV files inside the “Test” folder: … Read more

How to Write Data to a JSON File using Python

Here are 3 ways to write data to a json file using Python: (1) Single dictionary to a json file: Copy import json data = { “product”: “Computer”, “price”: 1300, “brand”: “A” } file_path = r”path to save the json file\file_name.json” with open(file_path, “w”) as file: json.dump(data, file, indent=4) Where: The resulted json file: Copy … Read more

Write List of Lists to CSV File in Python

To write a List of Lists to a CSV file in Python: Copy import csv data = [ [“value_1”, “value_2”, “value_3”], [“value_4”, “value_5”, “value_6”], [“value_7”, “value_8”, “value_9″] ] file_path = r”path to store the file\file_name.csv” with open(file_path, “w”, newline=””) as file: csv_writer = csv.writer(file) csv_writer.writerows(data) Example of Writing a List of Lists to a CSV … Read more

How to Resize an Image in Python

The PIL library can be used to resize an image in Python. In this short guide, you’ll see the full steps to resize your image. Steps to Resize an Image in Python (1) To start, install the PIL library using the following command: Copy pip install Pillow (2) Use the script below to resize your … Read more

Install the Matplotlib Package in Python

To install the Matplotlib package in Python: Copy pip install matplotlib Note that the above command would only work if you already added Python to the Path. Otherwise, check the steps below to install the Matplotlib package in Python. Steps to Install the Matplotlib Package in Python (1) Locate the Python Scripts folder using these steps: (2) … Read more