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

Python列表无法添加数据,写入TXT文件失败求助

问题排查与修复:Python读取文件分类数据失败

我写了一段Python代码,想读取lineup.txt里的数据,把属于Fenerbahçe(费内巴切)的球员存到fb列表,属于Trabzonspor(特拉布宗体育)的存到ts列表,再分别写入fb.txt和ts.txt。但运行后两个列表全是空的,根本写不进数据,找不到问题出在哪。

原代码

with open("lineup.txt", "r", encoding="utf-8") as file:
    ts = list()
    fb = list()

    for line in file:
        line = line[:-1]
        data = line.split(",")
        if (data[1] == "Fenerbahçe"):
            fb.append(line + "\n")
        elif (data[1] == "Trabzonspor"):
            ts.append(line + "\n")

    with open("ts.txt", "w", encoding="utf-8") as file1:
        for i in ts:
            file1.write(i)

    with open("fb.txt", "w", encoding="utf-8") as file2:
        for i in fb:
            file2.write(i)
print(fb)
print(ts)

lineup.txt 数据

U. Çakır, Trabozonspor
Marc Bartra, Trabzonspor
İ. Kahveci, Fenerbahçe
S. Aziz, Fenerbahçe
Trezeguet, Trabzonspor
A. Bayındır, Fenerbahçe
Gustavo Henrique, Fenerbahçe

问题根源

两个细节导致所有匹配条件都不触发:

  1. 拼写不一致:lineup.txt第一行的球队名写成了Trabozonspor(少了一个b),和代码中判断的Trabzonspor不匹配,直接漏掉了第一行数据。
  2. 空格残留:所有数据的逗号后都带了空格,比如"U. Çakır, Trabozonspor"用split(",")分割后,data[1]的值是" Trabozonspor"(前面带空格),而代码里判断的是无空格的"Trabzonspor",导致所有行的球队名都无法匹配。

修正后的代码

with open("lineup.txt", "r", encoding="utf-8") as file:
    ts = []
    fb = []

    for line in file:
        # 去掉首尾空白(包括换行符),避免不同系统换行符问题
        line_clean = line.strip()
        if not line_clean:
            continue  # 跳过空行
        
        data = line_clean.split(",")
        # 取出球队名并彻底去掉前后空格
        team = data[1].strip()
        
        if team == "Fenerbahçe":
            fb.append(line_clean + "\n")
        # 兼容拼写错误,也可以直接修改lineup.txt里的拼写
        elif team in ("Trabzonspor", "Trabozonspor"):
            ts.append(line_clean + "\n")

    # 用writelines直接写入列表,比循环逐个写更高效
    with open("ts.txt", "w", encoding="utf-8") as file1:
        file1.writelines(ts)

    with open("fb.txt", "w", encoding="utf-8") as file2:
        file2.writelines(fb)

print(fb)
print(ts)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:01:05