Search code examples
pythonpython-import

How to import and use a module with one line


I have this code that loads the natural gas storage numbers from the internet.

from urllib.request import urlopen
print(int(str(urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))

How could I do this in one line? More specifically, I was wondering how I could get rid of the import line and do something like this:

print(int(str(urllib.request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))

(I changed the urlopen call to urllib.request.urlopen. It would be sort of like Java, if you use the fully qualified name, you don't need an import statement.)


Solution

  • You always need the import, however you can still use semi-colons to separate statements:

    from urllib.request import urlopen; print(int(str(urllib.request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))
    #             note the semi-colon ^