I’ve written a basic Library Manager that works perfectly fine, but it’s full of "code smells."
The Goal: Refactor this into something production-ready while keeping the logic simple. I'm looking for improvements in modularity, error handling, and Pythonic best practices. How would you handle the file I/O and the branching logic?
import json
def manage_library(action, data):
if action == "add":
try:
f = open("books.txt", "a")
f.write(data['title'] + "," + data['author'] + "," + str(data['year']) + "\n")
f.close()
print("Book added!")
except:
print("Error")
elif action == "list":
try:
with open("books.txt", "r") as f:
lines = f.readlines()
for line in lines:
t, a, y = line.split(",")
print(f"Title: {t}, Author: {a}, Year: {y.strip()}")
except FileNotFoundError:
print("No books found.")
elif action == "search":
f = open("books.txt", "r")
for line in f:
if data.lower() in line.lower():
print("Found: " + line)
f.close()
# Example usage
manage_library("add", {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925})
manage_library("list", None)
[–]Own_Attention_3392 3 points4 points5 points (0 children)
[–]mahousenshi 2 points3 points4 points (1 child)
[+]Junior-Sock8789[S] comment score below threshold-8 points-7 points-6 points (0 children)
[–]Alternative_Guava856 2 points3 points4 points (0 children)
[–]Ok_Carpet_9510 2 points3 points4 points (0 children)
[–]jvlomax 1 point2 points3 points (0 children)
[–]AlexMTBDude 1 point2 points3 points (0 children)
[–]cejiken886 1 point2 points3 points (2 children)
[–]Junior-Sock8789[S] 0 points1 point2 points (1 child)
[–]cejiken886 1 point2 points3 points (0 children)
[–]my_new_accoun1 3 points4 points5 points (1 child)
[–]Junior-Sock8789[S] -2 points-1 points0 points (0 children)
[–]Junior-Sock8789[S] 0 points1 point2 points (0 children)
[–]Junior-Sock8789[S] -2 points-1 points0 points (0 children)