How to save python screen output to a text file

前端 未结 10 1013
星月不相逢
星月不相逢 2020-12-08 06:16

I\'m new to Python. I need to query items from a dict and save the result to a text file. Here\'s what I have:

import json
import exec.fullog as e

input = e         


        
10条回答
  •  执念已碎
    2020-12-08 06:43

    What you're asking for isn't impossible, but it's probably not what you actually want.

    Instead of trying to save the screen output to a file, just write the output to a file instead of to the screen.

    Like this:

    with open('outfile.txt', 'w') as outfile:
        print >>outfile, 'Data collected on:', input['header']['timestamp'].date()
    

    Just add that >>outfile into all your print statements, and make sure everything is indented under that with statement.


    More generally, it's better to use string formatting rather than magic print commas, which means you can use the write function instead. For example:

    outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))
    

    But if print is already doing what you want as far as formatting goes, you can stick with it for now.


    What if you've got some Python script someone else wrote (or, worse, a compiled C program that you don't have the source to) and can't make this change? Then the answer is to wrap it in another script that captures its output, with the subprocess module. Again, you probably don't want that, but if you do:

    output = subprocess.check_output([sys.executable, './otherscript.py'])
    with open('outfile.txt', 'wb') as outfile:
        outfile.write(output)
    

提交回复
热议问题