Extracting Digits from a File using Python

Day 34 #50DaysOfCodingChallenge Extracting Digits from a File using Python Today I worked on a simple but powerful file-processing problem. Here’s a breakdown of how my code works step by step 👇 🔹 1. Function Definition I created a function: def just_digits(file_path): This allows me to reuse the logic for any file path. 🔹 2. Open the File fr = open(file_path, "r", encoding="utf-8") Opens the file in read mode Uses UTF-8 encoding to avoid errors with special characters 🔹 3. Loop Through Each Line for line in fr Reads the file line by line instead of loading everything at once 🔹 4. Split Line into Words line.split() Breaks each line into individual words using spaces 🔹 5. Clean Each Word w.strip('.,“”"') Removes punctuation like commas, periods, and quotes Helps isolate pure numeric values 🔹 6. Check for Digits if w.strip(...).isdigit() Ensures only numbers are selected Filters out all text 🔹 7. List Comprehension Magic ✨ [ ... for line in fr for w in line.split() if ... ] Combines looping + filtering into one clean line Efficient and Pythonic way to process data 🔹 8. Return Result The function returns a list of numbers (as strings) 🔹 9. Function Call print(just_digits("python.csv")) Executes the function and prints output ✅ Final Output: ['1991', '2', '2000', '3', '2008'] 🚀 Key Learnings: Handling file encoding errors (UTF-8) Using .isdigit() for filtering data Writing compact logic using list comprehension Cleaning raw text data effectively Grateful for the guidance and support from Sajay N J Sir, Chithirakrishna Mv Ma'am and Neethu Unni M Ma'am. #Python #CodingChallenge #LuminarTechnolab

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories