Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take input file from terminal for python script?

Tags:

python

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.

like image 603
Hell Man Avatar asked Nov 23 '13 02:11

Hell Man


People also ask

How do I call a Python file from terminal?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


1 Answers

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:         o.write(line) 

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()

like image 153
Kyle Neary Avatar answered Oct 28 '22 18:10

Kyle Neary