首页 > 解决方案 > 将循环变量保存在不同的 CSV 文件中

问题描述

对于当前项目,我计划将在多个循环中生成的变量保存在不同的 CSV 文件中。

但是对于下面的脚本,我没有收到任何可用的输出,很可能是由于命令的错误顺序(修改了内容并收到了各种结果,例如 44 个空文件,只有文件 43 的完整内容等)。

是否有任何智能调整可以将输出逐个循环保存在 CSV 中?代码的对应部分如下所示:

# Allocate periods for individual CSV file names
    periods = pd.period_range('2009Q1','2018Q4',freq='Q')
    ts = pd.Series(np.random.randn(40), periods)
    type(ts.index)
    intervals = ts.index

    # Create individual file names
    for i in intervals:
        name = 'Glassdoor_A_' + str(i)

        # Print the contents of dictionary
        for key in list(d.keys()):
            print(key, ":", d[key])

            # Count the total number of words
            total = sum(d.values())
            percent = d[key] / total

            print(d[key], total, percent)

        # Save output in CSV file
        with open(name+'.csv', 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(["Word", "Occurrences", "Percentage"])
            writer.writerows([[key, val, val / total] for key, val in d.items()])

标签: pythonpython-3.xcsv

解决方案


推荐阅读