How to execute a python script and write output to txt file?

后端 未结 8 602
离开以前
离开以前 2020-12-10 14:31

I\'m executing a .py file, which spits out a give string. This command works fine

execfile (\'file.py\')

But I want the output (in addition to it being shown

8条回答
  •  遥遥无期
    2020-12-10 15:12

    using some hints from Remolten in the above posts and some other links I have written the following:

    from os import listdir
    from os.path import isfile, join
    folderpath = "/Users/nupadhy/Downloads"
    filenames = [A for A in listdir(folderpath) if isfile(join(folderpath,A))]
    newlistfiles = ("\n".join(filenames))
    OuttxtFile = open('listallfiles.txt', 'w')
    OuttxtFile.write(newlistfiles)
    OuttxtFile.close()
    

    The code above is to list all files in my download folder. It saves the output to the output to listallfiles.txt. If the file is not there it will create and replace it with a new every time to run this code. Only thing you need to be mindful of is that it will create the output file in the folder where your py script is saved. See how you go, hope it helps.

提交回复
热议问题