DEV Community

Adarsh Punj
Adarsh Punj

Posted on

🚀 5 Python One-Liners You Should Know

Format JSON

cat file.json | python -m json.tool
Enter fullscreen mode Exit fullscreen mode

The | operator is a "pipe" between the two commands, hence the output of cat is sent to Python's json.tool

Save a string to a file

print("Hello, World!", file=open('file.txt', 'w')) 
Enter fullscreen mode Exit fullscreen mode

The default value of file is sys.out, which leads it to print to the console.

Hidden user input

import getpass

pwd = getpass.getpass("ENTER PASSWORD:" )
Enter fullscreen mode Exit fullscreen mode

getpass is a built-in Python library

Validate spellings [EN]

Let's see if the word "hello" is a valid English word.

if "hello".casefold() in open('/usr/share/dict/words/').read(): return True
Enter fullscreen mode Exit fullscreen mode

Most of the unix-based machines have a "words" file in the system that is basically the English dictionary with 200k+ words. We can check if the given word exists in the dictionary to validate the spelling. The name and location of this file might be different for you.

Start a quick, local server

python -m http.server 8000
Enter fullscreen mode Exit fullscreen mode

This starts a local server on port 8000 from the current working directory

Source: Snekletter; weekly code nuggets.

Top comments (1)

Collapse
 
raddevus profile image
raddevus

Wow! Just tried that last one on Ubuntu 22.04.2 LTS with python3 and it worked great.
Thanks for sharing these valuable one-liners. They were very interesting.
I usually use $ http-server -p 8082 (nodejs http server) but this is a cool option using python.
If you get a chance, check out my latest article here on dev.to, Software Developer, Are You Just A Hammer? and let me know what you think.