You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 characters
    • imei_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.DictReader and csv.DictWriter because they let you reference columns by name (like row['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 the csv.reader/csv.DictReader calls.

内容的提问来源于stack exchange,提问作者Vvega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:31:22