【问题标题】:How to save command line file as .txt file every time. In CMD need to display the speedtest output save the those command line as .txt file如何每次将命令行文件保存为 .txt 文件。在 CMD 中需要显示 speedtest 输出,将这些命令行保存为 .txt 文件
【发布时间】:2020-02-19 12:39:24
【问题描述】:

这是下面给出的程序

导入操作系统 进口时间

  1. 索引=0
  2. file=open("out_{index}.txt", 'a')
  3. 当真:
  4. ps=os.system(f"speedtest.exe")
  5. file.append(ps)
  6. 索引+=1
  7. time.sleep(4)

【问题讨论】:

    标签: python-3.x networking automation


    【解决方案1】:

    我相信它是 file.write() 而不是 file.append()。

    我想你每次都想写入一个新文件。

    我会这样做。

    import time
    import os
    index = 0
    while True:
        ps = os.system("speedtest.exe")
        with open(f"out_{index}.txt", 'w+') as f:
            f.write(ps)
        index += 1
    time.sleep(4)
    

    但是,如果你想写在同一个文件中。

    我会这样做。

    import time
    import os
    with open("out_file.txt", 'a+') as f:
    index = 0
        while True:
            ps = os.system("speedtest.exe")
            f.write(ps)
            index += 1
    time.sleep(4)
    

    【讨论】:

    • 当我这段代码出现 f.write(ps) NameError: name 'f' is not defined 之类的错误时
    • @user11766050 是的,先生,我犯了一个错误。请使用编辑后的代码重试。我在打开函数后忘记了“as f”
    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2016-07-16
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多