0

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.

Created a test directory on the desktop

test directory contents

test.py
test1 -- folder
    sample.txt

contents of test.py

import os

dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
    print(file)

Summary - absolute path

  • works - in visual studio code
  • works - macOS terminal python3 /Users/username/Desktop/test/test.py

however when use the variable I get an error:

contents of test.py

import os

dataDir = "test1"
for file in os.listdir(dataDir):
    print(file)

Summary - relative path

  • works - in visual studio code
  • ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
    Traceback (most recent call last):
     File "/Users/username/Desktop/test/test.py", line 4, in 
        for file in os.listdir(dataDir):
    FileNotFoundError: [Errno 2] No such file or directory: 'test1'
Lacer
  • 5,668
  • 10
  • 33
  • 45

2 Answers2

0

I all depends on what folder you are in when you launch the code.

Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.

Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.

Fabio R.
  • 393
  • 3
  • 15
0

The following solution is inspired by that answer

A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)

First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).

But if you use the command line your actual working directory may change, depending where you're calling the script from.

To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.

To use your script correctly and being able to call it using both ways, the following implementation can help you:

import os

dataDir = "test1"

# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)

# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)

for file in os.listdir(absolutePath):
    print(file)
Chrissi
  • 189
  • 1
  • 8