Engineers often analyze data given in a Comma Separated Valu
Engineers often analyze data given in a Comma Separated Values (CSV) file. A CSV file is a plain text file in which data are organized into rows and columns. A newline character (In) makes a new line and a comma () separates adjacent columns. For example, the following file has five columns and three rows 11.2,20.3,-36.4,9.3,5.5 22.5,18.6,-16.2,3.2,0.9 34.2,-16.2,13.2,-8.9,7.2 In this assignment, write a Python function to perform the following: . Ask the user for the name of the CSV file to process Open the file for reading. Open another file with the name output.csv for writing. Read the input file line by line. . For each line, compute the sum and the average of the column values. Write to the file \"output.csv the original column values followed by the row sum and the row average as a valid CSV file. In other words, the output file will have two more columns than the input file and the same number of rows. . Close both files. A correct solution will generate the following data from the sample input file above and write the data into \"output.csv 11.2,20.3.-36.4,9.3,5.5,9.900000000000002,1.9800000000000004 22.5.18.6,-16.2,3.2,0.9,29.0,5.8 34.2.-16.2.13.2.-8.9,7.,-38.9,-7.779999999999999 To verify the content of the \"output.csv file, you may want to open it using a spreadsheet application (e.g, LibreOffice Calc or Microsoft Excel) or a text editor, e.g.. Notepad+ +
Solution
def csv():
print(\"CSV Data Analysis\")
print()
fname = input(\"Enter CSV file name:\")
file = open(fname,\"r\")
lines = file.read().split(\"\ \")
out = open(\"output.csv\",\"w\")
for line in lines:
data = line.split(\",\")
# convert to float data.
data = [float(x) for x in data]
# find sum
s = sum(data)
# find average
avg = s/len(data)
# writing to file
for i in data:
print(i,end=\",\",file=out)
print(s,end=\",\",file=out)
print(avg,end=\"\ \",file=out)
file.close()
out.close()
f = open(\"output.csv\",\"r\")
print(f.read())
csv()
\"\"\"
\"\"\"
