Miquel Torres Miquel Torres - 3 months ago 20
Python Question

codecs.open create txt file in specific path Python

i have this code but it saves the files in the same path of .py file, how can i do to create txt files in specific folder?

f = codecs.open("gabili" + '.txt', mode="w", encoding="utf-16")
reload(sys)
sys.setdefaultencoding('utf8')
f.write(u"[HELLO] *ASDASD* /(&) \n")

Answer

The codecs.open fonction takes a filename parameter. This filename can be a file name or a full path. So, you can use "/full/path/to/gabili.txt".

To build a full path, you can use os.path package, like this.

import os

fullpath = os.path.join("/full", "path", "to", "gabili.txt)

Then use it in codecs.open parameters:

with codecs.open(fullpath, mode="w", encoding="utf-16") as f:
    f.write(u"[HELLO] *ASDASD* /(&) \n")

NOTE1: the recommanded way to open a file is by using a with statement

NOTE2: to be portable Py2/Py3, you should use io.open instead of codecs.open

import io

with io.open(fullpath, mode="w", encoding="utf-16") as f:
    f.write(u"[HELLO] *ASDASD* /(&) \n")
Comments