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.
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'
Instead of using fileinput, open the file directly yourself:
import sys try: fileobj = open(sys.argv, 'r') except IndexError: fileobj = sys.stdin with fileobj: data = fileobj.read()
f = open('file.txt', 'r') data = f.read() f.close()
further more, to open a file passed from the command line you can do: (also, this is a smarter way to open files, instead of f = open(...) you can do with ...)
import sys with open(sys.argv, 'r') as f: data = f.read()
The reason for with being a smarter way to open files, is because it will automaticlly close the file after you leave the indented with block. This means you don't have to "worry" about files being open or forgotten for to long (that can cause "to many open filehandles" from your OS)
Then to sys.argv
sys.argv will be the first parameter on the command line after your python file. sys.argv will be your scripts name. for instance:
python myscript.py heeyooo will be:
- sys.argv == "myscript.py"
- sys.argv == "heeyooo" :)
Then there's all sorts of modules that will be interesting to you when working with files. For one, os.path is a good start because you will most likely want to do as much cross-platform as possible and this gives you the option to convert \ into / on Linux and vice versa. A few good ones are:
You also have os.getcwd() which might be good :)