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

登录认证与权限控制模块代码报错及文件创建问题求助

问题修复方案

1. TypeError: %d format: a number is required, not str 修复

这个错误是因为你在使用旧式字符串格式化时,错误地用了%d(整数占位符)来格式化字符串类型的变量。%d仅适用于整数,字符串需要用%s占位符,或者更推荐使用Python3.6+支持的f-string(语法更清晰,不易出错)。

错误示例:

# 假设new_username和new_user_type都是字符串
print("新增用户:%d,类型:%d" % (new_username, new_user_type))

修复方案:

方案1:替换占位符为%s

print("新增用户:%s,类型:%s" % (new_username, new_user_type))

方案2:改用f-string(推荐)

print(f"新增用户:{new_username},类型:{new_user_type}")

注意:全局检查代码中所有的%格式化语句,确保占位符和变量类型完全匹配。


2. Windows终端无法用touch创建userdata.txt 修复

touch是类Unix系统(Linux/macOS)的命令,Windows的CMD和PowerShell不支持该命令,你可以通过以下两种方式解决:

方案1:让Python代码自动创建文件(推荐)

在程序初始化时检查文件是否存在,不存在则自动创建空文件,避免用户手动操作:

# 在程序开头添加
import os

if not os.path.exists("userdata.txt"):
    with open("userdata.txt", "w", encoding="utf-8") as f:
        pass  # 创建空文件

方案2:Windows终端手动创建

  • CMD命令:
type nul > userdata.txt
  • PowerShell命令:
New-Item userdata.txt -ItemType File

额外优化建议(针对你的权限模块)

添加用户写入文件时,建议用CSV格式存储(每行用户名,密码,用户类型),方便后续读取解析:

# Admin添加用户时的写入逻辑示例
def add_user(username, password, user_type):
    with open("userdata.txt", "a", encoding="utf-8") as f:
        f.write(f"{username},{password},{user_type}\n")

用户认证时读取文件校验:

def authenticate(username, password):
    with open("userdata.txt", "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            stored_user, stored_pwd, stored_type = line.split(",")
            if stored_user == username and stored_pwd == password:
                return stored_type  # 返回用户类型,用于权限控制
    print("Incorrect password or username")
    return None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:07:07