0

This is a part of python script xyz.py.

#!/usr/bin/env python

from openpyxl import Workbook
import os
wb = Workbook()
path = "/home/Final_analysis/"
#print(os.listdir())
lis = os.listdir(path)

I wanted to use this script with different input files which are stored in different directories. For this script to run on multiple files I would have to change this part of the script every time.

path= "/home/Final_analysis/"

Can I parse the path as argument after python script for example

xyz.py path_to_my_file

in the command so that each time I don't have to change the script?

I tried running script as above after writing sys.argv[1] in path

#!/usr/bin/env python

from openpyxl import Workbook
import os
wb = Workbook()
path = "sys.argv[1]"
#print(os.listdir())
lis = os.listdir(path)

and ran command xyz.py /home/final_analysis

but it still doesn't detect the path. I am getting following error

Traceback (most recent call last):
  File "combine_excel.py", line 8, in <module>
    lis = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'sys.argv[1]'

I am using in python 2.7.6.

2
  • 5
    Did you mean sys.argv[1]? That should work. Does the path contain spaces? Commented May 18, 2018 at 11:42
  • Don't pass sys.argv[1] as a string, use it directly: path = sys.argv[1]. Don't forget to import sys before it, tho. Commented May 18, 2018 at 11:58

2 Answers 2

1

Don't pass sys.argv[1] as a string, use it directly: path = sys.argv[1]

#!/usr/bin/env python

from openpyxl import Workbook
import os
import sys
wb = Workbook()
path = sys.argv[1]
#print(os.listdir())
lis = os.listdir(path)

(per zwer's comment to the question.)

Sign up to request clarification or add additional context in comments.

Comments

0

In addition to what people have commented on you post, you can also use the "{}".format() syntax. A really clean way to insert string into an already formed string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.