user3476378 user3476378 - 1 year ago 58
Python Question

How to read and write to CSV Files in Python

I have a csv file, which has only a single column , which acts as my input.

I use that input to find my outputs. I have multiple outputs and I need those outputs in another csv file.

Can anyone please suggest me the ways on how to do it ?

Here is the code :

import urllib.request
jd = {input 1}
Some Codes to find output - a,b,c,d,e
** Code to write output to a csv file.
** Repeat the code with next input of input csv file.

Input CSV File has only a single column and is represented below:

Output would in a separate csv in a given below format :
It would be in multiple rows and multiple columns format.

a b c d e

ser ser
Answer Source

Here is a simple example:

The data.csv is a csv with one column and multiple rows.

The results.csv contain the mean and median of the input and is a csv with 1 row and 2 columns (mean is in 1st column and median in 2nd column)


import numpy as np
import pandas as pd
import csv

#load the data
data = pd.read_csv("data.csv", header=None)

#calculate things for the 1st column that has the data
calculate_mean = [np.mean(data.loc[:,0])]
calculate_median = [np.median(data.loc[:,0])]
results = [calculate_mean, calculate_median]

#write results to csv
row = []
for result in results:

with open("results.csv", "wb") as file:
   writer = csv.writer(file)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download