Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

command

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?

like image 642
afkmaster Avatar asked Sep 16 '11 01:09

afkmaster


People also ask

Can you read a Python file line by line?

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.


2 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
like image 190
jbeard4 Avatar answered Oct 18 '22 17:10

jbeard4


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

like image 20
odinho - Velmont Avatar answered Oct 18 '22 18:10

odinho - Velmont