passing variables to os.chdir in python -
I have a very disappointing experience trying to change the directory in Python using the variable in the program. Specifically, suppose I have:
index = '999' os.environ ['dir_name'] = 'directory_name_' + index os.chdir ('$ dir_name') < / Code>
The OSERR returns: [Aron 2] There is no such file or directory: '$ dir_name'
and yet
Os.system ('echo $ dir_name')
Returns' Directory_Name_999 '(a valid directory name) and so on
os.chdir (' Directory_Name_999 ')
Replaces the directory without error and what can Python do os.syst Em
understands that $ dir_name
is a named dir_name
. It checks its environment variable and finds it.
Python does not know what is "$ dir_name"
, and it assumes that you are using a literal string, it tries to change that directory , And fails because there is no literal directory "$ dir_name"
.
Instead, do:
Index = '999' os.environment ['dir_name'] = "directory_name_" + index os.chdir (os.environ [ 'Dir_name'])
You have the Ossystem ('cd $ dir_name')
means:
Code>
But why mess with system call? Just do it python.
Comments
Post a Comment