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

Question:

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:Usersphili>python C:UsersphiliPycharmProjectsMLspraaktest.py
Traceback (most recent call last):
  File "C:UsersphiliPycharmProjectsMLspraaktest.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.

Asked By: Philip T

||

Answers:

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!

Answered By: Chadee Fouad