2

I am a beginner in Python. I want to source the file which has a variable value. I am sourcing the variable value using command line argument option. I want to use this variable as a path parameter to source my file. I am saying it to the variable. Below is the code I am trying.

folder_name = 'abc'

execfile("/a/b/c/folder_name")

and I am expecting it will take the value of folder_name as abc and execute the file as

execfile("/a/b/c/abc")
2
  • Try execfile("/a/b/c/{}".format(folder_name)) Commented Feb 3, 2018 at 12:15
  • Thanks Maroun, its worked for me. Commented Feb 4, 2018 at 4:25

4 Answers 4

2

This can be done either with string concatenation, or with format - the latter being safer/better:

execfile("/a/b/c/" + folder_name)

execfile("/a/b/c/{}".format(folder_name)

For more info on format, see PyFormat

However you might want to consider if execfile is the right approach here! Other data formats can be a better option - e.g. pickle, json or yaml.

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

Comments

1

You could use .format() whenever you need to insert variable name into string:

execfile("/a/b/c/{0}".format(folder_name))

Note that {0} here corresponds to first argument that you pass to format function.

Similarly, {1}, {2},... corresponds to second, third,.. arguments of format function respectively.

You could also use % operator, but note that it is deprecated as of Python 3.1. 

1 Comment

Thanks a lot. Now, I can use multiple variables in the same exec comamnd.
0

As you say you are a beginner in Python then you should change your approach and should not use execfile

Instead consider using pickle or json.load to store data

Comments

0

You need something like this:

folder_name = 'abc'

execfile("/a/b/c/{folder_name}".format(folder_name=folder_name))

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.