0

I created a script in python which reads excel file and calculate date now i want to execute it with following command:

python your_script.py ./path/to/transactions.csv

My python script file code:

import csv

def csv_data(path):
    with open(path) as csv_file:
        readCSV = csv.DictReader(csv_file)

        for line in readCSV:
            col_from = line['from']
            col_to = line['to']
            col_ammount = line['amount']
            from_amount = int(float(col_ammount.lstrip('$').replace(',', ''))) - int(
                float(col_ammount.lstrip('$').replace(',', '')))
            to_amount = 0 + int(float(col_ammount.lstrip('$').replace(',', '')))
            print(col_from, '$'+str(from_amount), col_to, '$'+str(to_amount))

csv_data('transactions.csv')
habib
  • 63
  • 2
  • 15
  • Add some info. What error it gives you if trying to execute ? – lucians Sep 08 '17 at 12:15
  • 1
    Possible duplicate of [How to read/process command line arguments?](https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments) –  Sep 08 '17 at 12:16
  • actually i am new in python and i used pycharm to run python.I not know that how to run script via command line.can you please explain ? – habib Sep 08 '17 at 12:18
  • In your terminal, try to fire the command by typing python, will it lead you to the interpreter? – Mervyn Lee Sep 08 '17 at 12:20
  • yes it given me python version – habib Sep 08 '17 at 12:24
  • If you just want to open transactions.csv, just go in the folder where there is the script, right close click with the mouse button anch choose open cmd here (console or prompt or whatever) and type python your_script.py. If you want to input the name of the file from prompt go to read the code in the answer Gnorxan. – PythonProgrammi Sep 10 '17 at 05:47

2 Answers2

1

You need the sys library and then you can access the argument with sys.argv[1].

import sys
csv_data(sys.argv[1])
Gnorxan
  • 11
  • 4
0
import csv
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-f", "--file", required = True,
    help = "path of .csv file is stored")

args = vars(ap.parse_args())

file = joblib.load(args["file"])


def csv_data(path):
    with open(path) as csv_file:
        readCSV = csv.DictReader(csv_file)

        for line in readCSV:
            col_from = line['from']
            col_to = line['to']
            col_ammount = line['amount']
            from_amount = int(float(col_ammount.lstrip('$').replace(',', ''))) - int(
                float(col_ammount.lstrip('$').replace(',', '')))
            to_amount = 0 + int(float(col_ammount.lstrip('$').replace(',', '')))
            print(col_from, '$'+str(from_amount), col_to, '$'+str(to_amount))

csv_data('transactions.csv')

Open CMD and write python your_script.py --file path/file.csv

Let me know. I'm also new but I'm trying hard to learn..

lucians
  • 2,239
  • 5
  • 36
  • 64