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

Python读取逗号分隔文本文件时如何拆分字符串为单个元素列表

Fixing List Format Issues When Reading Comma-Separated Text Files

Let's break down what's going wrong here and fix it step by step:

The Problem

Your current code uses line.split() which splits on whitespace by default, but your text file uses commas as separators. That's why each entire line is being treated as a single element in your sublists. Also, you have an unused line ucost=unit_cost.read (missing parentheses, but since you don't use ucost, it doesn't affect the output—we can just remove it).

The Fixed Code

Here's the adjusted version that gives you your desired output:

unitcostlist_of_lists = []
# Use a file path variable for cleaner code
file_path = "/Users/amit/Downloads/NetworkDesign 3/small_example/unit_tran_cost.txt"

# Using a `with` statement is safer—it automatically closes the file when done
with open(file_path, "r") as unit_cost:
    for line in unit_cost:
        # Strip removes trailing newlines, split(',') breaks the line at commas
        inner_list = line.strip().split(',')
        unitcostlist_of_lists.append(inner_list)

# Verify the output
print(unitcostlist_of_lists)

What Changed?

  • line.strip(): Removes the newline character (\n) at the end of each line, so you don't get extra whitespace in your elements.
  • split(','): Tells Python to split each line using commas as the separator, instead of the default whitespace.
  • with statement: This is a best practice for file handling—it ensures the file is properly closed even if an error occurs, so you don't leave open file handles hanging around.

Running this code will produce your expected output:

[['4','16','8','4'],['6','6','6','9'],['12','15','7','8']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:58:54