1

I have a lot of Perl scripts that looks something like the following. What it does is that it will automatically open any file given as a command line argument and in this case print the content of that file. If no file is given it will instead read from standard input.

while ( <> ) {
    print $_;
}

Is there a way to do something similar in Python without having to explicitly open each file?

2 Answers 2

10

The fileinput module in Python's standard library is designed exactly for this purpose, and I quote a bit of code from the URL I just gave:

import fileinput
for line in fileinput.input():
    process(line)

Use print in lieu of process and you have the exact equivalent of your Perl code.

Sign up to request clarification or add additional context in comments.

3 Comments

The library reference manual has been my bloody bedside reading for a couple of weeks now. It's like so unfair that you have years more Python experience. o.O (but I appreciate the answers, nevertheless)
@msw It doesn't actually take years. If you just skim over it enough times you get a feel for what stuff is in there for you already, and what isn't-- even if you haven't actually used the relevant modules. There are always surprises, of course (robotparser? Yikes!). I expect it takes years to have done this accidentally, if anything. ;)
@msw, I agree with David -- I discovered Python in Dec '99, and less than a year later Steve Holden had already nicknamed me "the martellibot" for my copious answers on comp.lang.python;-).
0

You could look into sys.argv. It may help.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.