首页 > 解决方案 > Write Python output neatly in a txt file?

问题描述

I am trying to create a program that lists and saves all running services on my Windows machine to a txt file. I got it to work but it is not listing line by line like in my output in the Python shell. Also, there are added parenthesis I do not want. See output vs txt file screenshot below. Also, my code is below.

Output vs txt file

My Code so far:

import win32con
import win32service

#Define ListServices class
def ListServices():
    resume = 0
    accessSCM = win32con.GENERIC_READ
    accessSrv = win32service.SC_MANAGER_ALL_ACCESS

    #Open Service Control Manager
    hscm = win32service.OpenSCManager(None, None, accessSCM)

    #Enumerate Service Control Manager DB
    typeFilter = win32service.SERVICE_WIN32
    stateFilter = win32service.SERVICE_ACTIVE

    statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)

    for (short_name, desc, status) in statuses:
        #Save output to txt file
        f=open('MyServices.txt', 'w')
        f.write(str(statuses))
        f.close()
        #Print output and append 'Running' at the end of each line
        print(desc, status, '----------> Running') 

ListServices();

标签: pythonfile

解决方案


write不会像 do 那样附加换行符print,所以你应该自己处理它。另外,请注意,没有理由在每次迭代时打开和关闭文件。只要您需要,就让它保持打开状态:

with open('MyServices.txt', 'w') as f:
    for (short_name, desc, status) in statuses:
        f.write(str(statuses))
        f.write(os.linesep)
        #Print output and append 'Running' at the end of each line
        print(desc, status, '----------> Running') 

推荐阅读