0

I want to get the list of files at the location where my script is.

So let's say I have a directory - foo/bar

My script is at foo/bar/script.py

I run the script from foo

My script is this:

import os

print(os.listdir())

But when I run it from foo, I get the contents of foo and not foo/bar. I want to get the contents of the script's directory, not the current working directory.

So how do I do this?

sybrg
  • 199
  • 7
  • Sounds like you want to use **os.chdir** - try [this](https://stackoverflow.com/a/1810760/13228935) answer – LouieC Nov 21 '20 at 04:40
  • Does this answer your question? [How can I find script's directory with Python?](https://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python). Get the script's directory, then pass it to `listdir(path)`. – Gino Mempin Nov 21 '20 at 04:48

2 Answers2

0

Try this: Get the current location from sys.args and change your location and then get the list.

import os, sys

#print(sys.argv[0]) #check this for file location

os.chdir('\\'.join(sys.argv[0].split('\\')[:-1]))
print(os.listdir())

PS: I tested this on Windows, if you are on mac or linux you will have to split with '/'

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
-1

So try going into to foo/bar directory instead of the foo. inside the foo their is only another folder called bar and not a file, so you would only get the folder when u run it. If you are on windows go to Cmd type "cd foo/bar".

I hope this helped!

  • Hi, welcome to SO. Formatting your answers will look good. format it to make it more helpful for others – Trect Nov 21 '20 at 10:43