[Python] TIL there is a core module, fileinput, to quickly write a loop over standard input or a list of files

Python

One of the Perl's strengths is to be able to write text filters in a few lines, for example

# Shell one-liner:
# Adds 1 to all the numbers in the files
perl -i -wnle 'print $_+1' numbers1.txt numbers2.txt numbers3.txt ...

That is roughly equivalent to write in code

while(<>){ # Iterate over all lines of all the given files
    print $_ + 1; # Take the current line ($_) and print it to STDOUT
}

Anything written to STDOUT will replace the current line in the original file.

Fortunately, Python has a module that mimics this behavior as well, fileinput.

import fileinput

for line in fileinput.input(inplace=True):
    print(int(line) + 1)

In just three lines of code you have a text filter that opens all the files in sys.argv[1:], iterates over each line, closes them when finished and opens the next one:

python process.py numbers1.txt numbers2.txt numbers3.txt ...

Posted Oct 29, 2016, 7:46 AM UTC

1213
SirChristoffee•

Something I've found confusing with python is that you can open a txt file just with f=open ('file.txt') and do basic read and write super easy. But it's buried docs if your in them. I only happened to google it a few weeks ago. That should be easily accessible info!

on phone so finding it to link here is hard.

1
atsiderOP•

I have leaned the hard way that there are a lot of hidden gems inside the standard libraries of any language.

It seems boring to read it since you know most of the things beforehand, but in the end you always find something valuable.

1
Ekalugsuak•

You also have

with open("file.txt") as f:
    DO_STUFF_WITH_f
BACK_TO_HIGHER_SCOPE

... which automatically closes the file after the with-scope.

1
kankyo•

What did you search for that didn't find this?

1

That's not recommended. I'm not an expert and don't know why, but I know that bad things can happen if you open a file without properly closing it. Therefore, you should always open files like this:

with("file.txt", "r") as f:
    text = f.read()

This way, the file always gets closed, no matter what happens - if any exception of any kind, or control structure change or anything happens - the first thing that happens is that f.close() gets called.

You can even use this in functions:

def open_file(path):
    with open(path) as f:
        return f.read()

The file still gets closed.

1