python - 如何将打印的 for 循环值写入 csv 文件?
问题描述
我想将打印的移动平均线保存到名为“LabelX”的 csv 文件中。
import pandas as pd
import numpy as np
import csv
from statistics import mean
from itertools import islice
df = pd.read_csv("5714604.csv");
Input = df['water_level(ft below land surface)'];
N = 50
cumsum, moving_aves = [0], []
for i, x in enumerate(Input, 1):
cumsum.append(cumsum[i-1] + x)
if i>=N:
moving_ave = (cumsum[i] - cumsum[i-N])/N
#can do stuff with moving_ave here
moving_aves.append(moving_ave)
print(moving_ave)
输出看起来像这样,这很好。185.78499999999997 185.77059999999997 185.7552 185.7384 185.72120000000004 185.7038 185.68640000000002 185.67 185.65439996998999999
我只需要在完成之前将其保存到增量行而不是列的 csv 文件中。
解决方案
当您查看print
函数帮助条目时,您可以看到您可以指定应该写入的文件:
help(print) 关于内置模块内置函数打印的帮助:
打印(...)
打印(值,...,sep='',end='\n',文件=sys.stdout,flush=False)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
因此,您可以open
将 csv 文件传递给它,并在完成后关闭它。
例如
>>> f = open("test.txt", "w")
>>> print("Hello World", file=f)
>>> f.close()
另一种解决方案是使用write
而不是print
,因为这就是write
用途。
提示:要正确打开和关闭文件,您应该使用以下with
语法:例如
with open(path, "w") as file:
file.write("Hello world")
推荐阅读
- c++ - “标识符未定义”,试图从私有结构创建一个函数
- django - Django 将图像从 URL 保存到模型导致 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
- if-statement - SAS 错误:SUM 的空参数无效
- python - 使用 Python 通过目录中的多个 .csv 文件循环函数
- jupyter-notebook - 谷歌colab中的数据集丢失了?
- python - 使用前一个日期从现有列创建新的 Pandas 列
- apache-spark - 关于 spark 数据集中的 count 方法的问题?
- mysql - 我如何知道是什么促使自动 MYSQL 查询每天在我的网站上运行?
- google-sheets - 在 Google 表格中加入两个表并计算第二个表中的值
- python - 如何将类对象列表转换为其属性列表