0

This is my code:

import os
print(list(os.listdir('test')))

When I run the code in Pycharm it outputs the following: ['test.txt']

However, when I run the same file with windows command prompt I get this output:

(MLspraak) C:\Users\phili>python C:\Users\phili\PycharmProjects\MLspraak\test.py
Traceback (most recent call last):
  File "C:\Users\phili\PycharmProjects\MLspraak\test.py", line 2, in <module>
    print(list(os.listdir('test')))
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'test'

Why do I get different results and how can I fix it?

I am using a venv and I'm certain that I'm running the same python version.

  • `cd PycharmProjects\MLspraak` before running it? It depends on where your `test` directory is. `os.listdir('test')` is telling python to list the contents of the folder `test` in your current directory. Currently you're in `C:\Users\phili`. If the folder isn't within that directory, you need to `cd` to the directory it's in. – Axe319 Mar 24 '23 at 12:04
  • 'test' path is 'C:\Users\phili\PycharmProjects\MLspraak\test' so same directory as the python file – Philip T 2007 Mar 24 '23 at 12:09
  • So first `cd PycharmProjects\MLspraak` to change to the correct directory. I'd recommend looking up the concept of navigating through directories from command line or a terminal. `os.listdir('test')` uses _your_ current directory. Not the python file's directory. – Axe319 Mar 24 '23 at 12:10
  • 1
    'cd PycharmProjects\MLspraak' fixed it. Thank you. – Philip T 2007 Mar 24 '23 at 12:16

1 Answers1

0

That's because the program is probably running from a different directory (Pycharm directory vs. C:\Users)

I suggest trying the following on both:

import os
path = os.getcwd()
print(path)

I think the output you'll get in PyCharm will be different from the one on your command line.

Hope that helps!

Chadee Fouad
  • 2,630
  • 2
  • 23
  • 29
  • I think you're right. I got 'C:\Users\phili\PycharmProjects\MLspraak' in Pycharm and 'C:\Users\phili' in the command prompt – Philip T 2007 Mar 24 '23 at 12:14