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?
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
I think it is fileinputmuch nicer for this. Easy to use for simple scripts:
fileinput
import fileinput for line in fileinput.input(): process(line)
Then you can make python myscript.py file.txtor even connect it. Purrfect!
python myscript.py file.txt
https://docs.python.org/3/library/fileinput.html
import sys file_name = sys.argv[1] f = open(file_name) data = f.read() f.close()