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")

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'
>>>

Ok, thanks for the correction.

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

filepath = "C/myfolder/myfile.txt"
fout = open(filepath, "w")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.