How to Create a file in "my documents" folder?

Finding the user's "My Documents" path

  • Alright so I have this small program and it needs to create a small .txt file in their 'My Documents' Folder. Here's the code thing for that: textfile=open('C:\Users\MYNAME\Documents','w') lines=['stuff goes here'] textfile.writelines(lines) textfile.close() The problem is that if other people uses it, how do i change the 'MYNAME' to their account name? Sorry if I'm not so clear on my question.

  • Answer:

    Use os.path.expanduser(path), see http://docs.python.org/library/os.path.html e.g. expanduser('~/filename') This works on both Unix and Windows, according to the docs. Edit: forward slash due to Sven's comment.

Firetryer at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

You can do something similar what is shown in the answer to the question http://stackoverflow.com/questions/3858851/python-get-windows-special-folders-for-currently-logged-in-user. For theMy Documentsfolder path, useshellcon.CSIDL_PERSONALin theshell.SHGetFolderPath()function call instead ofshellcon.CSIDL_MYPICTURES.

martineau

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.