Skip to main content
 首页 » 编程设计

python之使用 os.path 写入带有变量名的输出文件

2025年05月04日15kevingrace

我正在尝试将模型估计的结果保存到文件中。我已经尝试了很多事情,但它不起作用,因为我显然没有正确地做。我什至不确定 os.path.join 是来自 os.path 的正确命令:

#output the vectors for winsize=5 and features=10 
study1_path = os.path.join("/Users/dlhoffman/Study 1/") 
print(study1_path) 
 
/Users/dlhoffman/Study 1/ 
 
ifttt_model.wv.save_word2vec_format("study1_path/vectors.txt", binary=False, total_vec=None) 

因为我必须多次估计这个模型并且我想节省一些暴力输入,我还想用超参数 winsize 和特征的值标记每个输出文件。

我想得到的文件名,例如 winsize=5 和 features=10 是:

 /Users/dlhoffman/Study 1/5w10fvectors.txt 

所以在上面的例子中,“5”和“10”来自变量 winsize 和 features 的值。我已经研究了示例和 os.path 模块文档,但对 python 的了解不够,无法了解我应该做的事情。有什么想法吗?

请您参考如下方法:

要生成自定义目录名称,您可以使用 format strings 轻松实现.例如:

>>> wf = [(1,3), (2,4), (5,10), (2,90)] 
>>> for w,f in wf: 
...     print '/Users/Study 1/{}w{}fvectors.txt'.format(w, f) 
... 
/Users/Study 1/1w3fvectors.txt 
/Users/Study 1/2w4fvectors.txt 
/Users/Study 1/5w10fvectors.txt 
/Users/Study 1/2w90fvectors.txt