How to save python screen output to a text file

前端 未结 10 984
星月不相逢
星月不相逢 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:30

    Here's a really simple way in python 3+:

    f = open('filename.txt', 'w')
    print('something', file = f)
    

    ^ found that from this answer: https://stackoverflow.com/a/4110906/6794367

    0 讨论(0)
  • 2020-12-08 06:32

    You would probably want this. Simplest solution would be

    Create file first.

    open file via

    f = open('<filename>', 'w')
    

    or

    f = open('<filename>', 'a')
    

    in case you want to append to file

    Now, write to the same file via

    f.write(<text to be written>)
    

    Close the file after you are done using it

    #good pracitice
    f.close()
    
    0 讨论(0)
  • 2020-12-08 06:33

    Let me summarize all the answers and add some more.

    • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

    • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

    • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

    • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-08 06:43

    I found a quick way for this:

    log = open("log.txt", 'a')
    
    def oprint(message):
        print(message)
        global log
        log.write(message)
        return()
    
    code ...
    
    log.close()
    

    Whenever you want to print something just use oprint rather than print.

    Note1: In case you want to put the function oprint in a module then import it, use:

    import builtins
    
    builtins.log = open("log.txt", 'a')
    

    Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)

    0 讨论(0)
  • 2020-12-08 06:44
    python script_name.py > saveit.txt
    

    Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies. For instance, By this, we can route the printed output of a Python script to a file to save it.

    0 讨论(0)
提交回复
热议问题