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

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

+5
source share
3 answers
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
+12
source

I think it is fileinputmuch nicer for this. Easy to use for simple scripts:

import fileinput
for line in fileinput.input():
    process(line)

Then you can make python myscript.py file.txtor even connect it. Purrfect!

https://docs.python.org/3/library/fileinput.html

+3
source
import sys

file_name = sys.argv[1]
f = open(file_name)
data = f.read()
f.close()
0
source

All Articles