Python将字符串和整数写入txt文件



我正在制作一个小程序,它可以获取系统的基本信息,并在控制台中输出信息,但我希望它能在C驱动器中创建一个文件夹,并在该文件夹中创建包含所有信息的txt文件。

当我运行程序时,它创建文件夹和txt文件;无";


def run_all_checks():
montior_cpu_times()
monitor_cpu_util()
monitor_cpu_cores()
monitor_cpu_freq()
monitor_RAM_Usage()
monitor_disk()
monitor_disk_usage()
monitor_network()

if not os.path.exists('C:System Information Dump'):
os.makedirs('C:System Information Dump')
save_path = 'C:System Information Dump'
file_name = "System Info Dump.txt"
completeName = os.path.join(save_path, file_name)
print(completeName)
file1 = open(completeName, "a")
file1.write (str(run_all_checks()))
file1.close()
#def file1():
#return run_all_checks()
#info = file1()
#file = open("System Info Dump.txt","a")
#file.write(str(info))
#file.close()
#file1()

注释的代码只是我尝试过但没有成功的一个例子。

您的run_all_checks不会返回任何内容。如果你不确定函数列表有多长。你可以保留一个函数列表,对其进行迭代并返回其值,甚至直接将值写入文件。类似这样的东西:

def run_all_checks():
return "testing"
def montior_cpu_times():
return "FUNC 1"
def montior_cpu_util():
return "FUNC 2"
def runtest2():
return "FUNC3"
funcs = [montior_cpu_times(), montior_cpu_util(), runtest2(), run_all_checks()]
for func in funcs:
print(func)

问题是run_all_checks()不返回任何内容。这就是为什么文本文件是空的。

例如,尝试:

def run_all_checks():
montior_cpu_times()
monitor_cpu_util()
monitor_cpu_cores()
monitor_cpu_freq()
monitor_RAM_Usage()
monitor_disk()
monitor_disk_usage()
monitor_network()
return "Checks ran successfully!"

最新更新