Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Can't run Python files, help!

I am on Windows 10, and whenever I try to run the Python files I make the command prompt either immediately crashes or brings up an error (depending on how I open the file).

If I go to Command Prompt and type in "python hello_world.py" (hello_world.py only contains one line of code which is print("Hello World!")) I get this error "python: can't open file 'hello_world.py': [Errno 2] No such file or directory"

If I go to Command Prompt, enter the Python Shell and then in a new line type in hello_world.py I get this error "Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'hello_world' is not defined"

If I go into the file explorer, and double click the file, then Command Prompt pulls up for a split second and then quits. Can someone please help me with this. I would really appreciate it!

1 Answer

You need to know two thing before you run your Python file: 1. What is your current folder, i.e. the directory you see in the prompt, its probably C:\Users\Yourusername> or something like that; 2. Where is your Python file, and how you can navigate into that folder from your current folder. The error message of your first attempt tells you that your Python file is not in your current folder, so you need to go to that folder. Once you are in that folder, you can simply run "python hello_world.py", and the computer will know which file you are talking about. It makes sense, right? You can use command "cd" to navigate through folders. for details on how to use basic commands, you can go to this link:

http://www.cs.princeton.edu/courses/archive/spr05/cos126/cmd-prompt.html

Alternatively, if navigating to the target folder is complex, you can do "python \path_to_your_python_file\hello_world.py", where \path_to_your_python_file\ is the absolute path of the folder that contains your hello_world.py file, in the format of "C:\XXXX\XXXXX\". This way you can run your python file at any folder.

All I mentioned above is based on command line operation, which is your first method. You don't run python file in python interactive shell (REPL) or by double clicking the .py file.