[英]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? 我有此代码,但是它将文件保存在.py文件的相同路径中,我该怎么做才能在特定文件夹中创建txt文件?
f = codecs.open("gabili" + '.txt', mode="w", encoding="utf-16")
reload(sys)
sys.setdefaultencoding('utf8')
f.write(u"[HELLO] *ASDASD* /(&) \n")
The codecs.open
fonction takes a filename parameter. codecs.open
功能采用文件名参数。 This filename can be a file name or a full path. 该文件名可以是文件名或完整路径。 So, you can use
"/full/path/to/gabili.txt"
. 因此,您可以使用
"/full/path/to/gabili.txt"
。
To build a full path, you can use os.path
package, like this. 要构建完整路径,可以使用
os.path
包,如下所示。
import os
fullpath = os.path.join("/full", "path", "to", "gabili.txt)
Then use it in codecs.open
parameters: 然后在
codecs.open
参数中使用它:
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 注意1:建议的打开文件的方法是使用
with
语句
NOTE2: to be portable Py2/Py3, you should use io.open
instead of codecs.open
注意2:要便携式Py2 / Py3,应使用
io.open
而不是codecs.open
import io
with io.open(fullpath, mode="w", encoding="utf-16") as f:
f.write(u"[HELLO] *ASDASD* /(&) \n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.