0

I am on windows 10, python 3.8.

I have a python script that needs to write to a file. If I execute this script from the same directory ('python runScript.py'), everything works as expected (also in VSCode). When I try to run this script from another location ('python C:/myproject/runScript.py'), it will not write. However, everything else works normal. Like printing what I actually want to write.

I tried to simplify my code for debugging:

testaa = 'stringabc'

with open('temp.txt', 'w') as f:
    f.write(testaa)

I tried .close() and .flush() as mentioned from other solutions.

What's going on?

6
  • 1
    From which location did you invoke python C:/myproject/runScript.py ? Commented May 26, 2020 at 20:19
  • 1
    Isn't this a matter of absolute and relative paths? Does it write temp.txt to C: in the other case? Commented May 26, 2020 at 20:19
  • 1
    open('temp.txt', 'w') creates the file in the current directory, which is not necessarily the same as the directory where the python script lives. Commented May 26, 2020 at 20:20
  • Where do you look for the file? Did you scan the HD looking for it? Commented May 26, 2020 at 20:21
  • @JohnGordon and other, I feel so stupid. The file was being saved into the directory where I in and not in the directory where the script is. Sorry, guys. Commented May 26, 2020 at 20:26

1 Answer 1

2

As mentioned in the comments, unless specifying the exact directory where you are saving the file, it will be saved to your current directory.

Your current directory could be anywhere in your drive. Since I had a file already with the same name in the directory where my python script was, it confused me thinking it was not writing to file. Meanwhile it was writing the whole time just the file was somewhere else.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.