[英]Python writing strings and integers to a txt file
我正在制作一個獲取系統基本信息的小程序,該程序可以正常工作並在控制台中輸出信息,但我希望 output 在 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 不返回任何內容。 如果您不確定 function 列表有多長。 您可以保留一個函數列表並對其進行迭代並返回其值,或者甚至直接將值寫入文件。 是這樣的:
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!"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.