Implement `read()` method for FileInput

The return value of fileinput.input() has a nice readline() method which allows us to use it to replace an open() call in some circumstances.

But it does not have a read() method, which would make it a more file-like object.

It seems like with this enhancement, it could be used e.g. as an argument to pandas.read_csv(), which would simplify the writing of pandas applications with flexibility to use stdin, or input from a file from the command line.

Example:

import fileinput

with open("f.csv") as f:
  print(f.readline())

with fileinput.input() as f:
  print(f.readline())

with open("f.csv") as f:
  print(f.read())

with fileinput.input() as f:
  print(f.read())

The final print fails:
AttributeError: 'FileInput' object has no attribute 'read'

Hm… fileinput is highly line-oriented, it keeps track of a per-file line count and an overall line count. It really does not attempt to be similar to the (much newer) io.TextIO class, all it has in common is readline() (that, and close() and context manager behavior).

I recommend that you try implementing a conforming read() method (i.e., one that also supports read(n) for any integer n) to see what it would take.

If you really just want all the text, try "".join(f). From reading the source it looks like that would do what you want.

Thank you. Yes that makes sense.
But note that the core of my issue is that panda read_csv (also very line-oriented) uses read(), and thus can’t be used with fileinput.
I’ll try to look at a read() implementation.

If you want to you can of course submit a feature request issue and a companion PR, but that won’t do you any good until 3.12 comes around and you are using that or later versions.

2 Likes