Skip to content
Advertisement

passing file path as command line parameter in python

I need to write something into files, which I am passing through command line in python. I am using the below code mycode.py

import csv
import sys

path = sys.argv[1]
row = ['4', ' Danny', ' New York']

with open(r"path" , 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)

When I execute it, the file is not written, but when I hardcode path as

 with open(r"C:UsersvenkatDesktoppythonsam.csv", 'w') as 
 csvFile:

the file is being written, Please let me know if I am missing anything.

One more requirement is I have to pass only the directory in open, and append some file name. For example: I can pass

C:UsersvenkatDesktoppython, sam.csv

I have to append to the directory in code.

Advertisement

Answer

You should use the path variable’s value.

Replace

with open(r"path" , 'w') as csvFile:

with

with open(path , 'w') as csvFile:
          ^^^^

If you want to append one file to a directory path, you could use os package.

file_path = os.path.join(path, file)
Advertisement