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

如何用Python循环和条件判断修改文本文件中指定车辆的租赁状态

问题解决方案

错误原因

  • 使用r+模式逐行读取文件时,文件指针会随着读取操作不断向后移动,此时直接执行write操作只会把内容追加到文件末尾,无法修改之前已经读过的对应行的内容。
  • 原有修改逻辑错误:仅向文件写入了R\n,并没有将修改后的整行内容回写,也没有覆盖原有内容,自然无法达到修改状态位的效果。
  • 额外逻辑bug:原判断条件没有加括号,运算符优先级问题会导致判断逻辑出错,且for循环的else块里多了非法的break语句,会触发语法报错。

修复后代码

from datetime import datetime
now = datetime.now()
dateandtime = now.strftime("%d/%m/%Y %H:%M:%S")

def rentVehicle():
    VehicleID = input("Please enter the vehicle ID you want to rent: ")
    # 先把文件所有内容读入内存,无需生成额外文件
    with open("Vehicle.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()
    
    found = False
    # 遍历所有行匹配目标车辆
    for i in range(len(lines)):
        l = lines[i].strip().split(",")
        if l[0] == VehicleID:
            found = True
            status = l[-1].strip()
            if status == "A":
                renterID = input("Please enter your ID: ")
                startingodometer = input("Please enter the current odometer reading: ")
                print("\nCar",l[0],"is rented to", renterID,"\n")
                print("\t	******************** Vehicle Details ********************\n")
                print("Vehicle ID =",l[0],"\t\tDescription =",l[1],"\t\tDaily Rate =",l[4],"\tStatus =",status,"\n")
                print("Renter ID =",renterID,"\tDate/time of rent =",dateandtime,"\tRent Starting Odometer =",startingodometer)
                # 修改当前行状态为R,保留换行符
                l[-1] = "R\n"
                lines[i] = ",".join(l)
                print("\nRenting vehicle is successful!")
            elif status == "R":
                print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
            break
    
    if not found:
        print("\nThe vehicle ID you entered does not exist. Please enter a valid vehicle ID.")
    else:
        # 将修改后的全部内容直接覆盖写入原文件,符合项目要求
        with open("Vehicle.txt", "w", encoding="utf-8") as f:
            f.writelines(lines)

rentVehicle()

核心修改说明

  • 先一次性读取所有文件内容到列表中,在内存中完成对应行的修改操作,避免了读写同时操作时文件指针偏移的问题。
  • 所有修改完成后一次性用w模式覆盖写入原文件,全程没有使用其他临时文件,完全符合项目要求。
  • 修复了原代码中的缩进错误、逻辑判断错误、非法break语句等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:15:04