afkmaster afkmaster - 1 month ago 7
Python Question

I want to read in a file from the command line in python

How do I read in a file from python at the command line? So let's say i have a text.txt file and I want to do python prefixer.py text.txt, how would I read in the text file in my prefixer.py?

Answer
import sys

f = open(sys.argv[1],"r")
contents = f.read()
f.close()
print contents 

or, better,

import sys
with open(sys.argv[1], 'r') as f:
    contents = f.read()
print contents