-2

I am doing small project in which I have to read the file from STDIN. I am not sure what it means, what I asked the professor he told me, there is not need to open the file and close like we generally do.

sFile = open ( "file.txt",'r')

I dont have to pass the file as a argument.

I am kind of confused what he wants.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • 1
    Googling "python stdin" would have answered this. – Alex Hall May 11 '16 at 21:19
  • Quite frankly if you told your professor "I don't know what STDIN means" and the only response was "you don't have to open a file like we generally do" **That is not a helpful response at all!** the response should have been something like "It is a file (more or less) that is opened before your program starts and can be accessed via `sys.stdin`" That would have been significantly more helpful to you! – Tadhg McDonald-Jensen May 12 '16 at 15:59

3 Answers3

0

import sys, then sys.stdin will be the 'file' you want which you can use like any other file (e.g. sys.stdin.read()), and you don't have to close it. stdin means "standard input".

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

Might be helpful if you read through this post, which seems to be similar to yours.

'stdin' in this case would be the argument on the command line coming after the python script, so python script.py input_file. This input_file would be the file containing whatever data you are working on.

So, you're probably wondering how to read stdin. There are a couple of options. The one suggested in the thread linked above goes as follows:

import fileinput 
for line in fileinput.input(): 
    #read data from file

There are other ways, of course, but I think I'll leave you to it. Check the linked post for more information.

Depending on the context of your assignment, stdin may be automatically sent into the script, or you may have to do it manually as detailed above.

Community
  • 1
  • 1
Monkeyanator
  • 1,346
  • 2
  • 14
  • 29
0

The stdin takes input from different sources - depending on what input it gets. Given a very simple bit of code for illustration (let's call it: script.py):

import sys

text = sys.stdin.read()

print text

You can either pipe your script with the input-file like so:

$ more file.txt | script.py

In this case, the output of the first part of the pipeline - which is the content of the file - is assigned to our variable(in this case text, which gets printed out eventually).

When left empty (i.e. without any additional input) like so:

$ python script.py

It let's you write the input similar to the input function and assigns the written input to the defined variable(Note that this input-"window" is open until you explicitly close it, which is usually done with Ctrl+D).

Gnoosh
  • 16
  • 1
  • 2