Predictive Hacks

Standard Input and Standard Output in Python

We will provide an example of how you read a file with the standard input and how to write the file with the standard output in Python. We could provide the following descriptions for the standard input and output:

  • Standard input – Is the “I/O stream” that reads and input.
  • Standard output – It writes the output to the ‘I/O stream”

The next graph provides some examples about redirections:

Redirections cheatsheet
Stackoverflow

Let’s provide an example of how we can get an input from a file with the standard input and to write a file with the standard output. The task is the following:

  • Write a Python script which takes file as standard input
  • It reverses the text of each line
  • It saves the standard output to a new file called output.txt

My stdinout.py is the one below:

import sys

stdin = sys.stdin

# Redirect sys.stdout to the file
sys.stdout = open('output.txt', 'w')

for line in stdin:
    if len(line)>0:
        print(line.strip()[::-1])
    
sys.stdout.close()

Assume that the example input called myfile.txt is the following:

1.George
2.Jim
3.Maria
4.Joe
5.Steve
6.Stella

Now we can run our script with the following command:

python stdinout.py < myfile.txt

Note the < which means that we redirected the standard input. Finally, we get the following output called output.txt:

egroeG.1
miJ.2
airaM.3
eoJ.4
evetS.5
alletS.6

As we can we, it reversed each line as expected!

Good job!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s