python - 将循环变量保存在不同的 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()])
解决方案
推荐阅读
- c# - 如何在 RazorEngine 中使用命名空间辅助函数?
- android - Galaxy S9 设备在模拟时一直显示为“离线”
- c# - 无法在 .NET Core 中获取自定义应用设置的价值
- terraform - 如何在顶层和模块之外嵌套 Terraform 堆栈
- java - 如何使用 Spring Data Mongo Mapper 和复合键指定键参数顺序
- c - 将一个指针数组连接并添加到另一个指针数组的一个索引中
- sql - 如何拆分SQL中每一行的数字?
- java - 非法块大小异常 解密时使用填充密码解密时输入长度必须是 16 的倍数
- c++ - EXEC BAD ACCESS 遍历向量
- python - 如何使用 Python + Numpy 获得组中的变异系数?