3

I am creating a file with the help of python programming language in my hard drive. The code I am using is:

file = open('test.txt','w')

file.write('Blah Blah')

file.close()

This code creates test.txt file in hard drive but the file is saved in the default location of project. I want to save the file in other location like desktop or somewhere else. Can anyone tell me how to do this.

I am using python 3.5

Thanks in Advance,

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42
  • 1
    did you try googling ? possible duplication: http://stackoverflow.com/questions/8024248/telling-python-to-save-a-txt-file-to-a-certain-directory-on-windows-and-mac – PYPL Feb 29 '16 at 19:09

2 Answers2

9

Just specify the location in a string variable and then added to the name of file you want to create with doing open:

import os
my_dir = 'C:\\Test\\My_Dir'
file_name = 'test.txt'
fname = os.path.join(my_dir, file_name)
file = open(fname,'w')
Community
  • 1
  • 1
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
  • 2
    _Please_ don't build file paths by string concatenation. It is very easy to get wrong, as you have here (you probably don't really want `C:\\Test\\My_Dirtest.txt`). [`os.path`](https://docs.python.org/3/library/os.path.html#module-os.path) exists for a reason. – ChrisGPT was on strike Feb 29 '16 at 19:13
  • 1
    @Chris...Yea...totally missed it...Thanks for the head's up – Iron Fist Feb 29 '16 at 19:17
7

You need to pass a full absolute or relative path when opening the file:

file = open('/My/Example/Desktop/test.txt','w')
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65