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
JavaScript
x
5
1
import fileinput
2
from bs4 import BeautifulSoup
3
f = fileinput.input()
4
soup = BeautifulSoup(f.read())
5
But I get
JavaScript
1
5
1
Traceback (most recent call last):
2
File "visual-studio-extension-load-times.py", line 5, in <module>
3
soup = BeautifulSoup(f.read())
4
AttributeError: FileInput instance has no attribute 'read'
5
Advertisement
Answer
Instead of using fileinput
, open the file directly yourself:
JavaScript
1
9
1
import sys
2
try:
3
fileobj = open(sys.argv[1], 'r')
4
except IndexError:
5
fileobj = sys.stdin
6
7
with fileobj:
8
data = fileobj.read()
9