etudou 2024-01-07 14:40 采纳率: 0%
浏览 22
已结题

环境:cisco packet tracer8.2.1想实验:读取的值写入文本文件中结果:无法写入,如何解决?

环境:cisco packet tracer8.2.1
想实验:读取的值写入文本文件中
结果:无法写入

from gpio import *
from time import *
from physical import *
from environment import *
from file import *
from os import *
from os.path import * #文件的判断位置
import math

def main():

    while True:
        t1=analogRead(1)
        print(exists("t1.txt"))
        t_1=(t1-0)*200/(1023-0)-100+0.5
        t2=analogRead(2)
        t_2=(t2-0)*200/(1023-0)-100+0.5        
        print(t_1)
        print(t_2)
        customWrite(0,str(t_1)+"\n"+str(t_2))
        file=open("t1.txt", "aw")
        file.write("-")
        file.write(str(t_1) + "\n" + str(t_2))
        file.close()
        delay(5000)

if __name__ == "__main__":
    main()


  • 写回答

14条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-01-07 14:40
    关注

    引自免费微信小程序:皆我百晓生

    你好,很抱歉在思科模拟器中使用truncate()方法进行清空文件内容是不被支持的。你可以尝试以下修改来解决问题:

    使用"wb"模式来写入文件,这将覆盖原有的内容。

    修改后的代码如下:

    from gpio import *
    from time import *
    from physical import *
    from environment import *
    from file import *
    from os import *
    from os.path import * #文件的判断位置
    import math
     
    def main():
        while True:
            t1 = analogRead(1)
            print(exists("t1.txt"))
            t_1 = (t1 - 0) * 200 / (1023 - 0) - 100 + 0.5
            t2 = analogRead(2)
            t_2 = (t2 - 0) * 200 / (1023 - 0) - 100 + 0.5        
            print(t_1)
            print(t_2)
            customWrite(0, str(t_1) + "\n" + str(t_2))
            
            filename = "t1.txt"
            file = open(filename, 'wb')
            file.write("-" + str(t_1) + "\n" + str(t_2) + "\n")
            file.close()
            
            delay(5000)
     
    if __name__ == "__main__":
        main()
    

    希望这可以解决你的问题。如有其他问题,请随时提问。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月9日
  • 创建了问题 1月7日