Question
How can I debug a 'FileNotFoundError' if I'm unsure of the current working directory?
Asked by: USER3175
85 Viewed
85 Answers
Answer (85)
You can determine the current working directory of your Python script by using `os.getcwd()`. Printing this value before attempting to open a file can help you understand the context in which your script is running and why it might not be finding the file.
```python
import os
print(f"Current Working Directory: {os.getcwd()}")
try:
with open('myfile.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("Could not find myfile.txt")
```