1

I'm trying to create a python script (with very limited knowledge) that will create a text document on the desktop of whoever runs the program. The section I have that should actually create the text file looks like so:

save_path = 'Desktop'
name_of_file = "examplefile"
completeName = os.path.join(save_path, name_of_file+".txt")        
file1 = open(completeName, "w+")
toFile = '''text'''
file1.write(toFile)
file1.close()

Everything works as intended when run in Visual Studio Code, but when run in CMD, I get the error:

  File "file.py", line 101, in <module>
    open(completeName, "w+")
FileNotFoundError: [Errno 2] No such file or directory: 'Desktop\\examplefile.txt'

When run in py.exe, it simply crashes.

I've used C:\Users\MyName\Desktop>py file.py and C:\Users\MyName\Desktop>python3 file.py to execute the script and had the same error, which I guess doesn't surprise me.

I've looked online quite a bit on how to solve this, but pretty much everything I've seen just restates using open(filename, "w+") to create a text file (which I already know) or is in regards to using PATH, which I don't think I need, but admittedly is not something I understand that well.

To summarize, I cannot figure out for the life of me why the script works exclusively in VS Code.

FlipFlrpn
  • 11
  • 1

1 Answers1

1

That's because of the way you've defined the path to the file.

You're trying to create the file Desktop\examplefile.txt. So, when you run your script, it looks for the Desktop directory from your current working directory (the path where you're running your script from) and creates the examplefile.txt file in there.

But the error that you're getting means that it isn't able to find the Desktop directory from your current working directory. That's because you're running it from C:\Users\MyName\Desktop and there's no Desktop directory inside that.

What you should be doing is using a path which will always resolve to the desired directory. For example, if you wanna create a file on the Desktop:

save_path = os.path.join(os.environ['USERPROFILE'], "Desktop")

This will always resolve to the user's Desktop directory on Windows.

On Windows, the USERPROFILE environment variable represents the path to the user's home directory.

And if you're looking for a cross-platform solution to get the user's home directory, you can use this:

# Python 3.5+
from pathlib import Path
home_path = str(Path.home())

# Python 2, <3.5
from os import path
home_path = path.expanduser("~")
Traction
  • 311
  • 3
  • 6
  • This worked perfectly, thank you. Think I recall seeing stuff similar to this, just never pieced it all together. – FlipFlrpn Mar 16 '20 at 12:49