0

As the title describes, I am not sure why, but the same code was working fine before I tested on reading/writing a file outside of the directory. I was testing on the desktop folder and got it to read and write fine so I switched the file back in the working directory and changed the code accordingly back to "file.txt" which in theory should just create/read the file in the same directory as my main.py file. But when I run the code it seems to create the file one folder out. I even tried "./file.txt" see if that fixed the issue and it did not.

The directory is

  • Python Projects
    • Day 24
      • main.py

and when the code runs, instead of creating file.txt in Day 24 folder it makes it under the python projects folder.

3
  • Why are you asserting that when you open simply "file.txt" that "in theory should just create/read the file in the same directory as my main.py file"? Without an absolute path it defaults to whatever current working directory is, and in your case it was the Python Projects directory. Commented Jun 1, 2024 at 3:54
  • I'm using "with open" not just open, sorry. I know this will automatically create the file if it doesn't exist, which I assume should be relative to where main.py is located, as that's the file that is creating the file. I found my issue I believe my terminal was opening one directory back when it executed the python code for some reason. Once I cd into the Day 24 folder it seemed to work fine. Commented Jun 1, 2024 at 4:14
  • The open call doesn't care if it's in a with context - the crux of the matter is that you had to set your working directory to Day 24 in order for the relative path to work the way you wanted, which is precisely what was being pointed out - please refer to the linked QnA for complete details (they address opening a file for reading, but in reality the act of opening for either reading or writing follows the same rules for relative paths). Commented Jun 1, 2024 at 4:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.