首页 > 解决方案 > 如何每次将命令行文件保存为 .txt 文件。在 CMD 中需要显示 speedtest 输出,将这些命令行保存为 .txt 文件

问题描述

这是下面给出的程序

导入操作系统导入时间

  1. 索引=0
  2. file=open("out_{index}.txt", 'a')
  3. 而真:
  4. ps=os.system(f"speedtest.exe")
  5. 文件附加(ps)
  6. 索引+=1
  7. 时间.sleep(4)

标签: python-3.xnetworkingautomation

解决方案


我相信它是 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)

推荐阅读