How can we save a text file we make using python in another directory?The default directory is always the directory in which , the program is ? is there any way to change this?Can this be done when we are creating the file (FILE=open(filename,"w"))

thanks in advance

How can we save a text file we make using python in another directory?The default directory is always the directory in which , the program is ? is there any way to change this?Can this be done when we are creating the file (FILE=open(filename,"w"))

thanks in advance

Instead of filename, you can give a path to a file in another directory to open. For example

from os.path import join as pjoin
filename = "myfile.txt"
path_to_file = pjoin("C:", "foo", "bar", "baz", filename)
FILE = open(path_to_file, "w")

Edited 7 Years Ago by Gribouillis: n/a

Gribouillis

I'm not sure if this has been fixed or not (perhaps you're using a newer version of Python where this bug has been eliminated) but when I use your path.join this is what I get:

>>> from os.path import join as pjoin
>>> pjoin("C:", "foo", "bar", "baz")
'C:foo\\bar\\baz'
>>>

This is in Python 2.6.2 and has always been this way. I'm not sure why, but I've always found that when using a drive letter in windows you always have to explicitly add backslashes like this:

>>> from os.path import join as pjoin
>>> pjoin("C:\\", "foo", "bar", "baz")
'C:\\foo\\bar\\baz'
>>>

In your case it might be simpler to hard code the thing ...

filepath = "C/myfolder/myfile.txt"
fout = open(filepath, "w")

Edited 7 Years Ago by vegaseat: n/a

This question has already been answered. Start a new discussion instead.