Aman Saraf
Aman Saraf

Reputation: 607

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: 
 1
 2
 3
 4
 5 

 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    

Upvotes: 0

Views: 6408

Answers (3)

seralouk
seralouk

Reputation: 33147

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)

Example:

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:
    row.append(result)

with open("results.csv", "wb") as file:
   writer = csv.writer(file)
   writer.writerow(row)

Upvotes: 2

jezrael
jezrael

Reputation: 863166

I think you need read_csv for reading file to Series and to_csv for writing output Series to file in looping by Series.iteritems.


#file content
1
3
5

s = pd.read_csv('file', squeeze=True, names=['a'])
print (s)
0    1
1    3
2    5
Name: a, dtype: int64

for i, val in s.iteritems():
    #print (val)
    #some operation with scalar value val
    df = pd.DataFrame({'a':np.arange(val)})
    df['a'] = df['a'] * 10
    print (df)
    #write to csv, file name by val
    df.to_csv(str(val) + '.csv', index=False)

   a
0  0

    a
0   0
1  10
2  20

    a
0   0
1  10
2  20
3  30
4  40

Upvotes: 1

user6165050
user6165050

Reputation:

In pseudo code, you'll do something like this:

for each_file in a_folder_that_contains_csv:  # go through all the `inputs` - csv files
    with open(each_file) as csv_file, open(other_file) as output_file:  # open each csv file, and a new csv file
        process_the_input_from_each_csv  # process the data you read from the csv_file
        export_to_output_file  # export the data to the new csv file

Now, I won't write a full-working example because it's better for you to start digging and ask specific questions when you have some. You're now just asking: write this for me because I don't know Python.

Upvotes: 1

Related Questions