Reading files using raw_input or argv
Question: I am [Learning Python the Hard
Way](http://learnpythonthehardway.org/book/ex15.html). How could I edit this
code to work with a file named `'bobsDetails.txt'`?

    
    
    from sys import argv
    script, filename = argv
    txt = open(filename)
    print "Here's your file %r:" % filename
    print txt.read()
    print "Type the filename again:"
    file_again = raw_input("> ")
    txt_again = open(file_again)
    print txt_again.read()
    


Answer: You want to look at
[fileinput](https://docs.python.org/2/library/fileinput.html)

Suppose I have this file:

    
    
    $ cat bobsDetail.txt
    File 'Bob's Detail'
    

I can write a simple loop that will either 1) process stdin or 2) open the
file name and process the contents:

    
    
    #!/usr/bin/python
    
    import fileinput
    for line in fileinput.input():
        print line
    

Now make that executable (Unix):

    
    
    $ chmod +x fi.py
    

Then you can process that any way it is presented:

    
    
    $ ./fi.py bobsDetail.txt
    File 'Bob's Detail'
    

Or,

    
    
    $ cat bobsDetail.txt | ./fi.py
    File 'Bob's Detail'
    

Then you can identify stdin vs file:

    
    
    for line in fileinput.input():
        if fileinput.isfirstline():
            if fileinput.isstdin():
                print 'stdin'
            else:
                print fileinput.filename()    
    
        print line
    

From a file

    
    
    $ ./fi.py bobsDetail.txt
    bobsDetail.txt
    File 'Bob's Detail'
    

From stdin:

    
    
    $ cat bobsDetail.txt | ./fi.py
    stdin
    File 'Bob's Detail'
    

