Reputation: 237
I have a series of scripts running for an automation project. One of the scripts creates a folder called "cloned_git_repo". The next script needs to look in that folder for the files to run conversions on. How can I get my Python script to automatically get to that folder to work from? This is the code:
result = [y for x in os.walk('/Users/user.name/Desktop/automation_project/cloned_git_repo') for y in glob(os.path.join(x[0], '*.csv'))]
Instead of hardcoding that directory path, how can I have it automatically get to the 'cloned_git_repo' and continue the rest of the program. It can't be hardcoded because different people on different machines will be running the script so '/Users/user.name/Desktop/automation_project/cloned_git_repo' will be different per machine. Thanks!
Upvotes: 1
Views: 130
Reputation: 26886
What you would do is to access an environment variable, e.g. $HOME
and your script would take over from that. This would be somewhat above Python (any script could do that).
In Python, you could use:
import os
HOME = os.getenv('HOME')
to get it.
A cleaner (and cross-platform) approach would be to use os.path.expanduser()
, e.g.:
import os
HOME = os.path.expanduser('~')
In both case, you should get the /Users/user.name
part of the path in HOME
, and you can take it from there.
For example:
result = [
y
for x in os.walk('/Users/user.name/Desktop/automation_project/cloned_git_repo')
for y in glob(os.path.join(x[0], '*.csv'))]
could become:
import os
HOME = os.path.expanduser('~')
result = [
y
for x in os.walk(os.path.join(HOME, 'Desktop/automation_project/cloned_git_repo'))
for y in glob(os.path.join(x[0], '*.csv'))]
A more flexible approach would be to use a higher level package, e.g. appdir
, which offers cross-platform methods for accessing a variety of standard paths.
Upvotes: 1