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

Python中使用.split()函数触发ValueError的问题求助

问题原因与修复方案

错误根源

  1. 格式不匹配:passwords.txt里存在没有|分隔符的行(比如空行、格式错误的记录),导致split("|")只返回1个元素,无法拆成user和passw两个变量,触发ValueError。
  2. 打印位置错误:你的print语句在for循环外面,就算没有报错,也只会输出最后一条账号密码,无法展示所有记录。

修复后的代码

master_pwd = input("What is your master password?")

def view():
    with open("passwords.txt", "r") as f:
        for line in f.readlines():
            data = line.rstrip()
            # 先检查行是否包含分隔符,避免拆包错误
            if "|" not in data:
                print(f"跳过格式错误的行: {data}")
                continue
            user, passw = data.split("|")
            # 将print放到循环内,打印每一条记录
            print(f"User: {user}, Password: {passw}")

def add():
    name = input("Account Name: ")
    pwd = input(" Password: ")

    with open("passwords.txt", "a") as f:
        f.write(name + "|" + pwd + "\n")


while True:
    # 修正拼写错误:exsisting → existing
    mode = input(" Would you like to add a new password or view existing ones (view, add) press q to quit? ").lower()
    if mode == "q":
        break

    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("invalid mode.")
        continue

额外建议

  • 可以先检查passwords.txt的内容,手动删除空行或格式错误的行,避免程序运行时出现跳过提示。
  • 如果需要允许密码里包含|,可以给split加第二个参数限制拆分次数:data.split("|", 1),这样只会拆分第一个|,后面的内容都归为密码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:59:59