Python help, please! How can I output the print to the file called \"precip_mont
ID: 675439 • Letter: P
Question
Python help, please! How can I output the print to the file called "precip_monthly.csv"?
Below is the code I have currently:
import csv
def getDataList(fileName):
dataFile = open(fileName, "r")
dataList = []
for line in dataFile:
dataList.append(line.strip().split(','))
return dataList
def monthavg(datalist):
d= datalist
monthlyaveragelist= []
tv=0
vta=0
month= d[0][0][5:7]
year= d[0][0][0:4]
for i in d:
v= float(i[5])
c= float(i[6])
if i[0][5:7] == month and i[0][0:4] == year:
vtimesc= v*c
tv= tv + v
vta= vta + vtimesc
ap= vta/tv
aptuple= (ap,i[0][0:7])
monthlyaveragelist.append(aptuple)
return monthlyaveragelist
b = getDataList('precipitation.csv')
b.pop(0)
c=monthavg(b)
print c
Explanation / Answer
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it. The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format.
The csv module defines the following function to write to a file:
csv.writer(csvfile, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
We can write the value of variable "c" to the csv file "precip_monthly.csv" as shown below:
import csv
with open('precip_monthly.csv', 'wb')as f:
writer = csv.writer(f)
writer.writerows(someiterable)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.