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'

Answers


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()

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[1], '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[1] will be the first parameter on the command line after your python file. sys.argv[0] will be your scripts name. for instance:

python myscript.py heeyooo will be:

  • sys.argv[0] == "myscript.py"
  • sys.argv[1] == "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:

  • os.path.abspath
  • os.path.isfile
  • os.path.isdir

You also have os.getcwd() which might be good :)


Need Your Help

WPF Application failing outside of Debug (release/debug) mode

c# wpf mvvm radio-button autocad-plugin

Just to clarify, I have fixed this problem temperately and just wanted to see if someone could expand on why this happened and possibly give me some insight as to how to fix it permanently. I am bu...

Difference between .php extension and AddType

php html .htaccess

Since I want to have PHP code run properly on my website, should I add

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.