Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over all lines of files passed on the command line?

Tags:

python

stdin

I usually do this in Perl:

whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

Now, I want to do this in Python. I tried sys.stdin but I have no idea how to do as I have done in Perl. How can I read the input?

like image 411
Tg. Avatar asked Apr 03 '09 19:04

Tg.


People also ask

How do you loop through every file in a directory?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do you continue a command in the next line?

The Windows command prompt (cmd.exe) allows the ^ (Shift + 6) character to be used to indicate line continuation. It can be used both from the normal command prompt (which will actually prompt the user for more input if used) and within a batch file.


1 Answers

Try this:

import fileinput
for line in fileinput.input():
    process(line)
like image 101
Don Werve Avatar answered Oct 13 '22 02:10

Don Werve