基于Python提取addr文件数据并计算年龄的格式化输出需求
Solution to Process Address File & Calculate Age
Here's a straightforward Python script that handles your requirements step-by-step:
import csv def process_addr_file(): # Read the addr file using DictReader for easy column access with open('addr', mode='r') as file: reader = csv.DictReader(file) records = list(reader) # Get valid current year input from user while True: try: current_year = int(input("Please enter the current year (e.g., 2018): ")) break except ValueError: print("Oops! That's not a valid year. Please enter an integer.") # Print formatted header and separator print(f"{'Name':<15} {'Phone':<12} {'Email':<20} {'Age':<5}") print("-" * 52) # Calculate age and print each record for record in records: birth_year = int(record['Year_of_Birth']) age = current_year - birth_year print(f"{record['Name']:<15} {record['Phone']:<12} {record['Email']:<20} {age:<5}") if __name__ == "__main__": process_addr_file()
Key Details:
- CSV Handling: Uses Python's built-in
csv.DictReaderto access columns by their header names (no messy index numbers), making the code easy to read and modify. - Input Validation: Includes a loop to ensure the user enters a valid integer for the current year, avoiding crashes from non-numeric inputs.
- Clean Output: String alignment (
<) creates a neatly organized table that matches your requested headers (Name,Phone,Email,Age). - Accurate Age Calculation: Computes age by subtracting the
Year_of_Birthfrom the input current year, which is precise for your use case.
Example Output (when current year is 2018):
Name Phone Email Age ---------------------------------------------------- Elizi Moe 5208534566 emoe@ncsu.edu 40 Ma Ta 4345667345 mta@yahoo.com 30 Diana Cheng 5203456789 dcheng@asu.edu 48
Just save this script in the same folder as your addr file, run it, and follow the prompt to enter the current year. It’ll handle the rest!
内容的提问来源于stack exchange,提问作者Nelson
相关产品推荐
相关产品推荐

