How to open files given as command line arguments in python?

Ram picture Ram · Nov 26, 2011 · Viewed 61.9k times · Source

I want my .py file to accept file I give as input in command line. I used the sys.argv[] and also fileinput but I am not getting the output.

Answer

Tadeck picture Tadeck · Nov 26, 2011

If you will write the following script:

#!/usr/bin/env python

import sys

with open(sys.argv[1], 'r') as my_file:
    print(my_file.read())

and run it, it will display the content of the file whose name you pass in the first argument like that:

./my_script.py test.txt

(in the above example this file will be test.txt).