python can't find file when running script from command promt; it works when ran in pycharm

37 Views Asked by At

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.

1

There are 1 best solutions below

1
Chadee Fouad On BEST ANSWER

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!