Hell Man Hell Man - 3 months ago 10x
Python Question

How to take input file from terminal for python script?

I have a python script which uses a text file and manipulate the data from the file and output to another file. Basically I want it to work for any text file input. Right now I readline from the file and then print the output to screen. I want the output in a file.

So user can type the following and test for any file:

cat input_file.txt | python script.py > output_file.txt.

How can I implement this in my script? Thank You.

cat is command in linux. I don't know how it works.


The best way to do this is probably to call the input and output files as arguments for the python script:

import sys
inFile = sys.argv[1]
outFile = sys.argv[2]

Then you can read in all your data, do your manipulations, and write out the results:

with open(inFile,'r') as i:
    lines = i.readlines()

processedLines = manipulateData(lines)

with open(outFile,'w') as o:
    for line in processedLines:

You can call this program by running python script.py input_file.txt output_file.txt

If you absolutely must pipe the data to python (which is really not recommended), use sys.stdin.readlines()