In this tutorial, I will explain how to call a function from another file in Python. Recently someone asked about calling a function from another file, which made me research this topic and I found several ways to achieve this task. I will share my findings with suitable examples and screenshots.
Call a Function from Another File in Python
Let’s assume we are working on a “USA Weather Analysis” project. We will create two files: main.py and weather_utils.py. The weather_utils.py file will contain utility functions related to weather data processing, and main.py will call these functions.
Read How to Read an Excel File in Python?
Step 1: Create weather_utils.py
First, we create a file named weather_utils.py and define a function that processes weather data:
# weather_utils.py
def get_average_temperature(temperatures):
"""
Calculate the average temperature from a list of temperatures.
Parameters:
temperatures (list): List of temperature readings (in Fahrenheit).
Returns:
float: Average temperature.
"""
if not temperatures:
return 0
return sum(temperatures) / len(temperatures)
def get_temperature_trend(temperatures):
"""
Determine the temperature trend (increasing, decreasing, or stable).
Parameters:
temperatures (list): List of temperature readings (in Fahrenheit).
Returns:
str: Temperature trend ('increasing', 'decreasing', 'stable').
"""
if temperatures[-1] > temperatures[0]:
return 'increasing'
elif temperatures[-1] < temperatures[0]:
return 'decreasing'
else:
return 'stable'Check out How to Import a Python File from the Same Directory?
Step 2: Create main.py
Now, we create another file named example.py where we will call the functions defined in weather_utils.py:
# example.py
from weather_utils import get_average_temperature, get_temperature_trend
def main():
# Sample temperature data for New York City
nyc_temperatures = [55, 57, 60, 62, 65, 64, 63]
# Calculate average temperature
avg_temp = get_average_temperature(nyc_temperatures)
print(f"The average temperature in NYC is {avg_temp:.2f}°F.")
# Determine temperature trend
trend = get_temperature_trend(nyc_temperatures)
print(f"The temperature trend in NYC is {trend}.")
if __name__ == "__main__":
main()Explanation
- Importing Functions: In
example.py, we import theget_average_temperatureandget_temperature_trendfunctions fromweather_utils.py. - Using Imported Functions: We call these functions with sample temperature data for New York City.
- Output: The script calculates and prints the average temperature and the temperature trend.
I executed the above example code and added the screenshot below.

Read How to Get File Size in Python?
Handle Relative Imports
In larger projects, you might have a more complex directory structure. For example:
usa_weather_analysis/
│
├── main.py
└── utils/
└── weather_utils.pyIn this case, you need to adjust the import statements to reflect the directory structure. In main.py:
from utils.weather_utils import get_average_temperature, get_temperature_trendExample
Let’s enhance our example by fetching real-time weather data. We will use the requests library to get weather data from an API.
Check out How to Overwrite a File in Python?
Step 1: Install requests
First, install the requests library if you haven’t already:
pip install requestsStep 2: Update weather_utils.py
Add a function to fetch weather data from an API:
# weather_utils.py
import requests
def fetch_weather_data(city):
"""
Fetch current weather data for a given city using OpenWeatherMap API.
Parameters:
city (str): City name.
Returns:
dict: Weather data.
"""
api_key = 'your_api_key_here'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=imperial'
response = requests.get(url)
return response.json()Read How to Rename Files in Python?
Step 3: Update main.py
Modify main.py to fetch and process real-time weather data:
# main.py
from weather_utils import get_average_temperature, get_temperature_trend, fetch_weather_data
def main():
city = 'New York'
weather_data = fetch_weather_data(city)
temperatures = [weather_data['main']['temp']]
# Calculate average temperature
avg_temp = get_average_temperature(temperatures)
print(f"The current temperature in {city} is {avg_temp:.2f}°F.")
# Determine temperature trend
trend = get_temperature_trend(temperatures)
print(f"The temperature trend in {city} is {trend}.")
if __name__ == "__main__":
main()Explanation
- Fetching Weather Data: We added the
fetch_weather_datafunction to get real-time weather data from OpenWeatherMap API. - Processing Data: The script fetches the current temperature for New York City and processes it to determine the trend.
Check out How to Check if a File is Empty in Python?
Error Handling and Validation
When calling functions from another file, it’s crucial to handle potential errors gracefully. For instance, the API call might fail, or the data might be incomplete. Update fetch_weather_data to include error handling:
# weather_utils.py
def fetch_weather_data(city):
api_key = 'your_api_key_here'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=imperial'
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
return NoneUpdate main.py for Error Handling
# main.py
def main():
city = 'New York'
weather_data = fetch_weather_data(city)
if weather_data:
temperatures = [weather_data['main']['temp']]
# Calculate average temperature
avg_temp = get_average_temperature(temperatures)
print(f"The current temperature in {city} is {avg_temp:.2f}°F.")
# Determine temperature trend
trend = get_temperature_trend(temperatures)
print(f"The temperature trend in {city} is {trend}.")
else:
print("Failed to fetch weather data.")
if __name__ == "__main__":
main()Read How to Get File Name Without Extension in Python?
Conclusion
In this article, I explained how to call a function from another file in Python. I discussed steps to call function from another file in Python, how to handle relative imports step-by-step with example. I also covered error handling and validation.
You may like to read:
- How to Clear a File in Python?
- How to Write Lines to a File in Python?
- How to Write Multiple Lines to a File in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.