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
?
Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.
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 fileinput
is a lot nicer for this. Easy to use for simple scripts:
import fileinput
for line in fileinput.input():
process(line)
Then you can do python myscript.py file.txt
or even pipe it in. Purrfect!
https://docs.python.org/3/library/fileinput.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With