How to read a file from command line using Python?

PythonServer Side ProgrammingProgramming

In order to read a file form command line using Python, the script you want to use for it needs to accept a CLI argument. For example, say you want to write a cat command in python(a command that dumps all file content on the terminal). In order to do that, you could simply write a program:

import sys
    contents =
print contents

If you save this file as and run it using:

$ python my_file.txt

This will take the my_file.txt and pass it to as a CLI argument in variable argv[1](second command line argument) which we can use to get the file and its contents.

Published on 26-Dec-2017 17:17:48