簡體   English   中英

如何將打印的 for 循環值寫入 csv 文件?

[英]How do I write printed for loop values to a csv file?

我想將打印的移動平均線保存到名為“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.7849999999997 185.77059999999997 185.7552 185.7384 185.72120000000004 185.7038 185.68640000695.68640006995.7552 185.7384

我只需要將它保存到 csv 文件中的增量行而不是列,直到完成。

當您查看print功能幫助條目時,您可以看到您可以指定一個文件應該寫入的位置:

help(print) 模塊內置函數中的內置函數打印幫助:

打印(...)

打印(值,...,sep='',end='\\n',file=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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM