Description of below code

To save the Python screen output to a text file, you can redirect the standard output to a file. Here’s the modified version of your code with explanations.

  • Import the `sys` module to access the standard output functionality.
  • Specify the desired file path (`output.txt`) to save the output.
  • Use a `with` statement to open the file in write mode (‘w’) as ‘f’.
  • Save a reference to the original standard output (`original_stdout`).
  • Redirect the standard output to the file by assigning `sys.stdout` to ‘f’.
  • Print the desired output, and it will be written to the file instead of the console.
  • After the block, we reset the standard output to its original value.

This code will save the printed output to the specified text file (`output.txt`). You can change the `output_file_path` variable to your preferred file path.

import json
import exec.fullog as e

inp = e.getdata()  # inp now is a dict() which has items, keys, and values.
# Query
output_file_path = 'output.txt'  # Set the desired file path
# Redirecting standard output to a file
with open(output_file_path, 'w') as f:
    original_stdout = sys.stdout  # Save a reference to the original standard output
    sys.stdout = f  # Redirect standard output to the file

    print('Data collected on:', inp['header']['timestamp'].date())
    print('\n CLASS 1 INFO\n')

    for item in inp['Demographics']:
    	if item['name'] in ['Carly', 'Jane']:
        	print(item['name'], 'Height:', item['ht'], 'Age:', item['years'])

    for item in inp['Activity']:
    	if item['name'] in ['Cycle', 'Run', 'Swim']:
        	print(item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years'])
    sys.stdout = original_stdout  # Reset standard output to the original value

 

Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Related Q&A