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

如何用Python读取特定格式多行TXT文件并转为指定二维数组

Solution to Convert Text File to 2D Array in Python

Got it, let's walk through how to turn that text file into the 2D array you're looking for. The key here is cleaning up each line properly since your file has trailing commas and possible extra spaces.

Step-by-Step Code Implementation

Here's a straightforward, robust script that handles the formatting quirks in your file:

# Initialize an empty list to hold our 2D array
two_d_array = []

# Open the file using a context manager (auto-closes the file when done)
with open('your_file.txt', 'r') as file:
    # Loop through each line in the file
    for line in file:
        # Process the line:
        # 1. Strip leading/trailing whitespace (like newlines or extra spaces at line ends)
        # 2. Split the line into individual items using commas as separators
        # 3. Clean each item by stripping its own whitespace, and filter out empty strings (from trailing commas)
        cleaned_row = [item.strip() for item in line.strip().split(',') if item.strip()]
        # Add the cleaned row to our 2D array
        two_d_array.append(cleaned_row)

# Check the result
print(two_d_array)

How This Works

Let's break down the important parts:

  • Context Manager (with open(...)): This is the safest way to handle files in Python—it automatically closes the file after we're done, so you don't have to remember to call file.close().
  • Line Cleaning: The list comprehension [item.strip() for item in line.strip().split(',') if item.strip()] does three things:
    • Splits the line into a list using commas
    • Removes any extra spaces around each item (like the space before g in your example)
    • Filters out empty strings that come from the trailing comma at the end of each line
  • Building the 2D Array: Each cleaned row gets added to two_d_array, resulting in exactly the structure you want: [['a','b','c','d','e','f'], ['g','h','i','j','k','l']]

Test Case

If your your_file.txt looks like this:

a,b,c,d,e,f,
g,h,i,j,k,l,

Running the script will output:

[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l']]

This code will also handle minor variations, like extra spaces between commas or leading/trailing spaces on lines, so it's pretty flexible.

内容的提问来源于stack exchange,提问作者A. Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:10:54