0

I am working with CSV file and in my code, for every CSV file that I want to process, I should change the input file name manually and it is taking some times to do that every time.

My code looks as follow:

import pandas as pd
file = pd.read_csv('data_0.csv', error_bad_lines=False);

I want to use the command line argument, to make the process easier and enter any CSV file that I want as an input.

for example:

python code.py data_0.csv 

save by desire name. for example:

python code.py data_0.csv output_0.csv

Now, I already read many posts such as 1, 2, 3, but I am not sure which one is faster and easier. Python documentation has many options such as sys.arg or argparse but I couldn't able to do it.

Thanks

Bilgin
  • 499
  • 1
  • 10
  • 25

1 Answers1

2

sys.argv would work for this problem: https://www.pythonforbeginners.com/system/python-sys-argv

import pandas as pd
import gensim
import numpy as np
import string
from sys import argv

# read CSV input file
file = pd.read_csv(sys.argv[1], error_bad_lines=False);

"""" Here my code performs some actions! """"

# Save the output into CSV
df.to_csv(sys.argv[2], index=True, mode = 'a')

(where sys.argv[0] here being code.py)

  • thanks for your comment. I tried to run as ```python mYcode.py data_0.csv``` but did not work. Also tried for ```python mYcode.py data_0.csv, output_0.csv``` as well. Can you let me know how I should run with this? thanks – Bilgin Jun 13 '19 at 18:40
  • I tried and i am getting error as ``` Traceback (most recent call last): File "mYcode.py", line 34, in file = pd.read_csv(sys.argv[1], error_bad_lines=False); NameError: name 'sys' is not defined ``` – Bilgin Jun 13 '19 at 18:46
  • apologies, its `import sys` not `from sys import argv` – time_is_a_drug Jun 13 '19 at 18:50