Skip to content
Advertisement

How to read a whole file in Python? To work universally in command line

How to read a whole file in Python? I would like my script to work however it is called

  • script.py log.txt
  • script.py < log2.txt
  • python script.py < log2.txt
  • python -i script.py logs/yesterday.txt

You get the idea.


I tried

import fileinput
from bs4 import BeautifulSoup
f = fileinput.input()
soup = BeautifulSoup(f.read())

But I get

Traceback (most recent call last):
  File "visual-studio-extension-load-times.py", line 5, in <module>
    soup = BeautifulSoup(f.read())
AttributeError: FileInput instance has no attribute 'read'

Advertisement

Answer

Instead of using fileinput, open the file directly yourself:

import sys
try:
    fileobj = open(sys.argv[1], 'r')
except IndexError:
    fileobj = sys.stdin

with fileobj:
    data = fileobj.read()
Advertisement