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

时间:2018-03-22 23:06:08

标签: python filenames os.path

我正在尝试将模型估算的结果保存到文件中。我尝试了很多东西,但它不起作用,因为我显然没有正确地做到这一点。我甚至不确定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和features来标记每个输出文件。

我想说的文件名,winsize = 5和features = 10是:

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

所以在上面的例子中,“5”和“10”来自变量winsize和features的值。我研究过这些例子& os.path模块文档,但不知道足够的python来获取我应该做的事情。有什么想法吗?

4 个答案:

答案 0 :(得分:3)

要生成自定义目录名称,您可以使用format strings轻松完成此操作。例如:

struct ThreadProperties {
    // thread specific
    id,
    slept for,
    is locked,
    is waiting,
    is joined,
    has mutex, if so hold id to mutex - lockguard
    is shared,
    is active,
    has promise or future...
    who has ownership of,
    marked for release,
    marked for transfer

    // other mutex and lock_guard properties

    // function object address stored as `size_t` to represent an id
    // data object address stored as `size_t` to represent an id

    // etc.

};

class ThreadManager {
private:
    std::map<unsigned, ThreadProperites> threadTable;
public:
    default constructor

    storeIds into relevant containers

    store properties into relevant containers

    associate above containers into a map or lookup table

    find or look for specific ID and if found 
    check to see its current status and report it
    also check to see if it's in a priority queue 
    or task scheduler and determine if it is ready
    to do something, or change its internal state.

    other common methods of functionality associated with threads.
};

// function templates to act on threads according to the reporting of the manager above.

答案 1 :(得分:2)

您可以根据需要格式化包含文件名的字符串以包含变量。字符串格式(以一种方式)就像这样工作

"number_%d" % (5) == "number_5"

当你在字符串中使用python中的%运算符时,它会将元组中的参数放在运算符的右边,并将它们放入字符串中。在这种情况下,%d会被int取代。 %s替换为str%f替换为浮点数。 <{1}}被被序列化对象的%r方法取代。

以下示例

__str__()

答案 2 :(得分:1)

我认为您要搜索的是这样的

file_name = os.path.join("folder_path", f"{variable}_vectors.txt")

,您还需要:

import os

位于文件顶部。

答案 3 :(得分:0)

我玩了一些,这有效!

#final step - write the results of this cell to a csv
#file contains word, word count, v1-vn

path=r'/Users/dlhoffman/Study 1/'
filename_template="%dw%df_words-vectors.csv"
filename=filename_template % (winsize, features)
vectors.to_csv(os.path.join(path, filename), index=False)