0

When I make this code into an executable the function of writing a file works, but it writes to a random directory. I'm not sure how to get it to write to my desktop, like it did when it was a regular python file.

Here is my code,

def write(): print('Creating a new file') name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt try: file = open(name,'w') # Trying to create a new file or open one file.close() except: print('Something went wrong! Cannot tell what?') sys.exit(0) # quit Python 
3
  • 1
    specify the full path for the file Commented Feb 15, 2016 at 17:41
  • Python will write to the current directory if not otherwise specified. Commented Feb 15, 2016 at 17:50
  • "Desktop" depends on your operating system and/or window manager. Commented Feb 15, 2016 at 17:55

2 Answers 2

1

You need to specify the path you want to save to. Furthermore, make use of os.path.join (documentation) to put the path and filename together. You can do something like this:

from os.path import join def write(): print('Creating a new file') path = "this/is/a/path/you/want/to/save/to" name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt try: file = open(join(path, name),'w') # Trying to create a new file or open one file.close() except: print('Something went wrong! Cannot tell what?') sys.exit(0) # quit Python 
Sign up to request clarification or add additional context in comments.

2 Comments

What is the point of the try and except block?
@ZacharyChiodini - I stuck with the OP's original code which already has that try/except. As to the point? it depends. In this case it seems like the application wants to fail on any exception that could raise and just give a "generic" output to the user. Whether it is helpful or not is a different discussion. Similarly, one can ask why not have a more narrow exception (e.g. only catch OSError) and provide more context in the message? Or if still using a broad exception, why not analyze the exception object that is raised and output more context to the user?
0

It is not writing into a random directory. It is writing into current directory, that is the directory you run it from. If you want it to write to a particular directory like your desktop you either need to add the path to the file name or switch the current directory. The first is done with

 name = os.path.join('C:\Users\YourUser\Desktop', name) 

the second is done with

 os.chdir('C:\Users\YourUser\Desktop') 

Or whatever the path to your desktop is.

1 Comment

You might also want to check if the user already appended path information to the file name in the input, like what if someone enters "C:\Windows\System32\rundll.exe" at the prompt.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.