Python读取文本指定列及列对齐格式化问题
Fixing Column Alignment for Your Text File Output
Got it, let's work through this alignment issue step by step. The core problem here is twofold: incorrect extraction of the item name (since it can contain spaces) and misconfigured formatting for clean alignment.
First, Diagnose the Issues in Your Existing Code
- You’re using
split('\t')but your file uses spaces as separators, not tabs. This meansline.split('\t')[3]won’t correctly grab the item name (it’ll throw an index error or return invalid data). - Item names like "Men's Clothing" have spaces, so a simple
split()breaks them into multiple elements—you can’t just pick index 3 directly. - The fixed
>33formatting adds excessive, unneeded space and doesn’t adapt to the actual length of your item names, leading to messy alignment.
Corrected Solution
We’ll first properly extract item names (even those with spaces) and then dynamically align output based on the longest item name in your file:
# Collect all item-price pairs correctly sales_data = [] with open("sample.txt", "r") as file: for line in file: # Split line into parts, but handle items with spaces parts = line.strip().split() # Item name spans from the 4th field (index 3) to just before the price item_name = ' '.join(parts[3:-2]) # Price is always the second-last element price = parts[-2] sales_data.append((item_name, price)) # Calculate longest item name length for perfect alignment max_item_length = max(len(item) for item, _ in sales_data) # Print aligned columns for item, price in sales_data: # Left-align item to max length, right-align price with fixed width print(f"{item:<{max_item_length}} {price:>6}")
What This Does
- Safe File Handling: Using
withensures the file is properly closed after reading, avoiding resource leaks. - Accurate Item Extraction:
' '.join(parts[3:-2])captures all elements from the 4th field up to just before the price, so items with spaces are kept as single strings. - Dynamic Alignment: Calculating
max_item_lengthensures all item names are left-aligned to the same width, while prices are right-aligned for a clean, consistent look.
Sample Output
Running this code with your sample file will produce exactly the aligned output you want:
Men's Clothing 214.05 Women's Clothing 153.57 Music 66.08
内容的提问来源于stack exchange,提问作者john tan
相关产品推荐
相关产品推荐

