如何将CSV文件中的15位IMEI号格式化为指定带空格形式?
How to Reformat 15-Digit IMEIs in a CSV File Using Python
Looks like you're halfway there! Let's finish up that code to reformat those IMEIs into the "XX XXXXXX XXXXXX X" format you need. Here's a complete, robust solution:
Complete Code Solution
import csv def reformat_imei(imei): # Convert to string and clean up any extra whitespace imei_str = str(imei).strip() # Validate it's a 15-digit number before formatting if len(imei_str) != 15 or not imei_str.isdigit(): # Return original if invalid (adjust to raise error if preferred) return imei_str # Slice the string into the required segments and format with spaces return f"{imei_str[:2]} {imei_str[2:8]} {imei_str[8:14]} {imei_str[14]}" # Get input file name from user file_csv = input("Enter file name: \n") output_file = f"formatted_{file_csv}" # Read original CSV and write formatted data to a new file with open(file_csv, "r", newline='') as infile, open(output_file, "w", newline='') as outfile: # Use DictReader if your CSV has headers (easier to reference columns by name) reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames) # Write the header row first writer.writeheader() # Process each row for row in reader: # Replace 'IMEI' with your actual column name (e.g., 'IMEI_Number') imei_column_name = 'IMEI' row[imei_column_name] = reformat_imei(row[imei_column_name]) writer.writerow(row) print(f"Success! Formatted CSV saved as {output_file}")
Key Details Explained
1. The IMEI Reformatting Function
The reformat_imei function handles all the heavy lifting:
- Converts the input to a string (in case your CSV stores IMEIs as numbers) and strips any extra spaces.
- Validates that the IMEI is exactly 15 digits (skips formatting if it's invalid, so you don't get broken strings).
- Uses string slicing to split the 15-digit string into the required parts:
imei_str[:2]: First 2 charactersimei_str[2:8]: Next 6 characters (indices 2 to 7 inclusive)imei_str[8:14]: Next 6 characters (indices 8 to 13 inclusive)imei_str[14]: Last 1 character (index 14, since Python uses 0-based indexing)
2. CSV Handling
- We use
csv.DictReaderandcsv.DictWriterbecause they let you reference columns by name (likerow['IMEI']) instead of indices, which is more readable and less error-prone. - We write to a new file (
formatted_yourfile.csv) instead of overwriting the original, so you don't lose your raw data.
3. If Your CSV Doesn't Have Headers
If your CSV doesn't use column headers, switch to csv.reader and use column indices instead:
# Alternative code for CSV without headers with open(file_csv, "r", newline='') as infile, open(output_file, "w", newline='') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) # Skip this line if there's no header row writer.writerow(next(reader)) for row in reader: # Assuming IMEI is in the second column (index 1; change to match your CSV) imei_column_index = 1 row[imei_column_index] = reformat_imei(row[imei_column_index]) writer.writerow(row)
Edge Cases to Consider
- If some entries in your CSV aren't 15-digit IMEIs, the function will leave them as-is. You can modify the validation step to raise an error or flag invalid entries if needed.
- Make sure your CSV uses standard formatting (comma-separated values). If it uses a different delimiter (like tabs), add
delimiter='\t'to thecsv.reader/csv.DictReadercalls.
内容的提问来源于stack exchange,提问作者Vvega
相关产品推荐
相关产品推荐

