PyCharm中path.exists()函数在不同目录下无法正常工作
Hey there! Let's figure out why path.exists() is behaving oddly for your directories in PyCharm. Here are some practical fixes to try out:
Double-check path spelling and case sensitivity
Operating systems like Linux and macOS are case-sensitive, so if your actual directory is namedkick_startbut your code usesKick_Start(or any variation in capitalization),path.exists()will return False. Print the absolute path to verify what Python is looking for:import os print(os.path.abspath("kick_start"))Compare this output to the actual directory path in your file system to spot any mismatches.
Verify your working directory
PyCharm's run configuration might be using a different working directory than you expect. Add this line to your code to check where Python is currently operating:import os print(os.getcwd())If the output isn't your
python_Jan 2020directory, adjust the working directory in PyCharm's run settings (Run -> Edit Configurations... -> Working directory) to point directly to that parent folder.Use absolute paths instead of relative paths
Relative paths can get messy if your code runs from a subdirectory. Try using absolute paths withpathlibfor more reliability:from pathlib import Path # Get the absolute path to your parent directory parent_dir = Path("python_Jan 2020").resolve() # Check if kick_start exists print((parent_dir / "kick_start").exists())Rule out permission issues
While unlikely for directories in the same parent folder, make sure you have read access tokick_startand other problematic directories. Try navigating to them manually in your file explorer to confirm you can open them without restrictions.Refresh PyCharm's file index
Sometimes PyCharm's cached file index gets out of sync with the actual file system. Go toFile -> Invalidate Caches... -> Invalidate and Restartto refresh the index, then re-run your code to see if the issue is fixed.
内容的提问来源于stack exchange,提问作者optimistic-zia

