Experiment No.
- 08
Aim: To develop Python code that allows the user to perform file handling operations such as reading,
writing, appending, clearing content and deletion.
Software: Python 3.13 as Interpreter and PyCharm as Integrated Development Environment.
Theory:
Program:
import math
# Required for trigonometric functions used in distance calculation
# ---------- Sample Fire Station Data ----------
# Each station has a name, latitude, longitude and a list of
available equipment
stations = [
{"name": "Central Fire Station", "lat": 21.1458, "lon": 79.0882,
"equipment": ["Ladder Truck", "Hose", "Foam", "Pump"]},
{"name": "North Station", "lat": 21.1800, "lon": 79.1000,
"equipment": ["Rescue Van", "Pump", "Water Tanker"]},
{"name": "South Station", "lat": 21.1200, "lon": 79.0700,
"equipment": ["Ladder", "Water Tank", "Foam"]},
{"name": "East Station", "lat": 21.1400, "lon": 79.1300,
"equipment": ["Truck", "First Aid", "Ladder"]},
{"name": "West Station", "lat": 21.1350, "lon": 79.0500,
"equipment": ["Hose", "Foam", "Rescue Kit"]}
]
# ---------- Haversine Formula Function ----------
# Calculates the distance between two coordinates using lat/lon
def haversine(lat1, lon1, lat2, lon2):
R = 6371 # Earth’s radius in kilometers
phi1 = math.radians(lat1)
1
Python Programming Lab File Handling
# Convert latitude of point 1 to radians
phi2 = math.radians(lat2)
# Convert latitude of point 2 to radians
d_phi = math.radians(lat2 - lat1)
# Difference in latitude in radians
d_lambda = math.radians(lon2 - lon1)
# Difference in longitude in radians
# Haversine formula
a = math.sin(d_phi / 2)**2 + math.cos(phi1) * math.cos(phi2)
* math.sin(d_lambda / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
return R * c # Distance in kilometers
# ---------- Function to Write Station Data to File ----------
def write_station_data(filename):
with open(filename, ’w’) as file:
for s in stations:
# Convert equipment list to semicolon-separated string
eq = ’;’.join(s["equipment"])
# Write one line per station
file.write(f"{s[’name’]},{s[’lat’]},{s[’lon’]},{eq}\n")
print(f"\nFire station data saved to {filename}")
# ---------- Function to Read and Display Station Data ----------
def read_station_data(filename):
try:
with open(filename, ’r’) as file:
print("\n--- Fire Station Records ---")
for line in file:
parts = line.strip().split(’,’) # Split line by commas
# Display each station’s data in readable format
Dr. D. K. Singh 2 National Fire Service College, Nagpur
File Handling Python Programming Lab
print(f"Name: {parts[0]}")
print(f"Lat: {parts[1]}, Lon: {parts[2]}")
print(f"Equipment: {parts[3].replace(’;’, ’, ’)}\n")
except FileNotFoundError:
print("Error: File not found.")
# ---------- Function to Clear/Delete Station File ----------
def delete_station_file(filename):
with open(filename, ’w’) as file:
file.write("") # Overwrite file with empty content
print(f"\n{filename} has been cleared.")
# ---- Function to Find Nearest Fire Station to a Fire Location -------
def find_nearest_station(fire_lat, fire_lon):
nearest = None # Variable to store the nearest station
min_dist = float(’inf’) # Start with very large distance
for s in stations:
# Compute distance to each station
d = haversine(fire_lat, fire_lon, s[’lat’], s[’lon’])
if d < min_dist:
min_dist = d
nearest = s
return nearest, min_dist # Return nearest station and distance
# ---------- Main Menu System ----------
datafile = "fire_station_data.txt"
# File where station data will be stored
while True:
# Menu for user interaction
print("\n===== FIRE STATION MENU =====")
print("1. Save Fire Station Data to File")
National Fire Service College, Nagpur 3 Dr. D. K. Singh
Python Programming Lab File Handling
print("2. Read Fire Station Data from File")
print("3. Find Nearest Fire Station to Fire Location")
print("4. Delete Data File")
print("0. Exit")
choice = input("Enter choice: ")
if choice == ’1’:
# Save predefined station data to file
write_station_data(datafile)
elif choice == ’2’:
# Read and display data from file
read_station_data(datafile)
elif choice == ’3’:
try:
# Ask user for fire location coordinates
lat = float(input("Enter Fire Location Latitude: "))
lon = float(input("Enter Fire Location Longitude: "))
# Get nearest station based on coordinates
nearest, distance = find_nearest_station(lat, lon)
# Display result
print(f"\nNearest Station: {nearest[’name’]}")
print(f"Distance: {distance:.2f} km")
print(f"Available Equipment: {’, ’.join(nearest[’equipment’])
}")
except ValueError:
print("Invalid input. Enter valid coordinates.")
elif choice == ’4’:
# Delete or clear file contents
delete_station_file(datafile)
elif choice == ’0’:
# Exit the program
print("Exiting system.")
Dr. D. K. Singh 4 National Fire Service College, Nagpur
File Handling Python Programming Lab
break
else:
print("Invalid choice. Try again.")
Program Output: File Handling
===== FIRE STATION MENU =====
1. Save Fire Station Data to File
2. Read Fire Station Data from File
3. Find Nearest Fire Station to Fire Location
4. Delete Data File
0. Exit
Enter choice: 1
Fire station data saved to fire_station_data.txt
===== FIRE STATION MENU =====
1. Save Fire Station Data to File
2. Read Fire Station Data from File
3. Find Nearest Fire Station to Fire Location
4. Delete Data File
0. Exit
Enter choice: 2
--- Fire Station Records ---
Name: Central Fire Station
Lat: 21.1458, Lon: 79.0882
Equipment: Ladder Truck, Hose, Foam, Pump
Name: North Station
Lat: 21.18, Lon: 79.1
Equipment: Rescue Van, Pump, Water Tanker
National Fire Service College, Nagpur 5 Dr. D. K. Singh
Python Programming Lab File Handling
Name: South Station
Lat: 21.12, Lon: 79.07
Equipment: Ladder, Water Tank, Foam
Name: East Station
Lat: 21.14, Lon: 79.13
Equipment: Truck, First Aid, Ladder
Name: West Station
Lat: 21.135, Lon: 79.05
Equipment: Hose, Foam, Rescue Kit
===== FIRE STATION MENU =====
1. Save Fire Station Data to File
2. Read Fire Station Data from File
3. Find Nearest Fire Station to Fire Location
4. Delete Data File
0. Exit
Enter choice: 3
Enter Fire Location Latitude: 21.15
Enter Fire Location Longitude: 79.00
Nearest Station: West Station
Distance: 5.45 km
Available Equipment: Hose, Foam, Rescue Kit
===== FIRE STATION MENU =====
1. Save Fire Station Data to File
2. Read Fire Station Data from File
Dr. D. K. Singh 6 National Fire Service College, Nagpur
File Handling Python Programming Lab
3. Find Nearest Fire Station to Fire Location
4. Delete Data File
0. Exit
Enter choice: 0
Exiting system.
National Fire Service College, Nagpur 7 Dr. D. K. Singh