简体   繁体   中英

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

I would like to save the printed moving average to a csv file named "LabelX".

    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)

The output looks like this which is fine. 185.78499999999997 185.77059999999997 185.7552 185.7384 185.72120000000004 185.7038 185.68640000000002 185.67 185.65439999999998 185.6398

I just need it saved to a csv file in incremental rows not columns until completion.

When you look at the print function help entry you can see that you can specify a file where it should write to:

help(print) Help on built-in function print in module builtins:

print(...)

print(value, ..., 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.

So you can open the csv file pass it and after you finished you close it.

eg

>>> f = open("test.txt", "w")
>>> print("Hello World", file=f)
>>> f.close()

Another solution would be to use write instead of print , because this is what write is for.

Tip: To open and close a file properly you should use the with syntax: eg

with open(path, "w") as file:
    file.write("Hello world")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM