【问题标题】:Python: Create folders and recursively store data from arrayPython:创建文件夹并递归存储数组中的数据
【发布时间】:2014-09-24 12:01:27
【问题描述】:

我需要递归地创建目录并将来自多个数组的数据输出存储在每个目录中。例如,我目前有:

    output_lat=zip(name_lat[0], lat[0])
    output_a = zip(name_a[0], full[0], a_type[0])
    f=open('geo.out','w')
    for line in output_lat:
            f.write(" ".join(str(x) for x in line) + "\n")
    for line in output_a:
            f.write(" ".join(str(x) for x in line) + "\n")

这将创建一个具有我想要的格式的输出“geo.out”。但由于“name_lat”、“lat”、“name_a”、“full”和“a_type”都是数组(长度相同),我想先创建一个主文件夹,然后创建以每个地理元素命名的子文件夹.dat 文件打印在其中。

例如,我希望将输出存储在诸如“~/main/geo##/geo##.dat”之类的文件夹中,其中## 是数组的索引。

任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: python arrays python-2.7 recursion output


    【解决方案1】:

    您只需将用于创建这些目录的行添加到您的代码中。另一方面,我不认为 “递归” 描述了你正在尝试做的事情。

    def output(output_a, output_lat, ouput_dir):
    
        # First create the hole directory structure.
        # -------------------------------------------
        ouput_path = os.path.join(ouput_dir, "geo{0}".format(index))
        # Check ouput directory existence.
        if not os.path.exists(os.path.join(ouput_dir, "geo{0}".format(index))):
            os.mkdir(ouput_path)
    
        for i in range(len(output_lat)):
            folder_name = os.path.join(ouput_path, "geo{0}".format(index))
            try:
                os.mkdir(folder_name)
            except OSError, e: 
                print("Error creating output dir: {0}".format(e))
    
        # Then create output files.
        # --------------------------------------------
        for index, (o_lat,o_a) in enumerate(zip(output_lat, output_a)):
            folder_name = os.path.join(ouput_path, "geo{0}".format(index))
            with open(os.path.join(folder_name, "geo{0}.dat".format(index)), "w+") as f:
                for line in o_lat:
                    f.write(" ".join(str(x) for x in line) + "\n")
                for line in o_a:
                    f.write(" ".join(str(x) for x in line) + "\n")
    

    【讨论】:

    • 对不起,我是新手,也许我的意思是“循环”。无论如何,当我运行它时似乎发生了一些奇怪的事情,我得到了错误:
    • 回溯(最近一次调用最后一次):文件“”,第 1 行,在 文件“pool.py”,第 128 行,在池中打开(os.path.join (folder_name, "geo{0}.dat".format(index)), "w+") as f: IOError: [Errno 2] No such file or directory: 'initial_pool/geo2/geo0/geo0.dat'跨度>
    • 我认为它会在每个 geo1、geo2 等内部创建一个额外的目录。我只需要一个文件夹用于其中的每个文件夹,其中包含相应的数据文件。例如'initial_pool/geo1/geo1.dat"
    • 答案已编辑希望对您有所帮助。如果您在我的帮助下想通了,请支持答案。 ;)
    猜你喜欢
    • 2017-05-31
    • 1970-01-01
    • 2014-04-09
    • 2015-03-03
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2015-06-14
    • 2021-11-24
    相关资源
    最近更新 更多