Mac OSX执行Python脚本遇Error [2]:找不到文件或目录
Hey Sam, let's get that hello.py script running—this is a typical file path issue on macOS, and it's easy to fix once we straighten out the details!
Why you're seeing the "No such file or directory" error
When you run python hello.py in Terminal, the shell looks for hello.py only in your current working directory. If you're not in the folder where the file lives, or if you're typing an incomplete/incorrect path, Terminal can't find it. Your previous attempts used either folder paths instead of the file itself, or truncated paths that didn't point directly to hello.py.
Step-by-step fixes
Let's go through the most reliable ways to resolve this:
First, confirm the exact path to hello.py
Open Terminal and run this command to locate the file automatically:find ~/Documents -name "hello.py"This will spit out a full path like
/Users/sam/Documents/Python/hello.py—that's the exact location we need to use.Option 1: Navigate to the file's folder first
- Use the
cdcommand to move into the directory wherehello.pyis stored. Using the path from step 1, that would be:cd ~/Documents/Python - Now you can run the script directly:
Note: If you get a "command not found" error forpython hello.pypython, trypython3instead—macOS defaults to Python 2 for thepythoncommand, but most modern tutorials use Python 3.
- Use the
Option 2: Run the script using its full path
If you don't want to navigate folders, you can run the script by typing its complete path right afterpython(orpython3):python ~/Documents/Python/hello.py
Quick note on your previous attempts
python ~/Users/sam/Documents/Python/Googlepoints to a folder, not thehello.pyfile—Terminal can't run a folder as a script!python exercises/google-python-exercise...uses a truncated path, so Terminal can't resolve where the actualhello.pyis located. Always use the full, exact path to the file.
Give these steps a try, and you should have that script running in no time!
内容的提问来源于stack exchange,提问作者Sam

