import re
# this regular expression matches lines like " abcd = feg ; "
CONFIG_LINE = re.compile("^\s*(\w+)\s*=\s*(\w+)\s*;")
# this takes { "variable_1":"a", "variable_2":"b", "variable_3":"c" }
# and turns it into "folder_a_b_c"
DIR_FMT = "folder_{variable_1}_{variable_2}_{variable_3}".format
def read_config_file(fname):
with open(fname) as inf:
matches = (CONFIG_LINE.match(line) for line in inf)
return {match.group(1):match.group(2) for match in matches if match}
def make_data_file(variables, contents):
dir = DIR_FMT(**variables)
fname = os.path.join(dir, "data.txt")
with open(fname, "w") as outf:
outf.write(contents)
def main():
variables = read_config_file("template.cfg")
make_data_file(variables, "this is my new file")
if __name__=="__main__":
main()
你能記錄你想要在引用的例子中創建的文件名(帶路徑)嗎? – user590028
是的,這是可能的。這是否回答你的問題? – lanzz
user590028:比方說,我想要名爲「folder_value_1_value_2_value3」的文件夾中名爲「data.txt」的文件。 lanzz:你能告訴我該怎麼做嗎? – user3116130