Search code examples
pythoncsvcsvwriter

Write in the next column of CSV file in python


I have a simple code that should write values in two columns, I would like to have the results shown as: 0.48 2.71 But I can only write in rows, how do I write the rows in the second column (I want to have the fines percentages in one column and 'X' in the second column)? your help is much appreciated. Here is the code:

import csv
finespacking = 0.55
d63fine= 2
coarsepacking= 0.6
d63coarse = 5
x=[]
percentage_fines_agg= [0.48,0.49,0.50,0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,0.60] 
rows = [[data] for data in x]
for item in percentage_fines_agg:
    with open ('tempmix.csv') as temp_mix_file:
        x= (item/(1-item))* (coarsepacking/finespacking)/(1-coarsepacking)
        writer= csv.writer(temp_mix_file)
        writer.writerows(rows)

Solution

  • If you want to do this without Pandas you could do something like:

    import csv
    
    
    finespacking = 0.55
    coarsepacking = 0.6
    factor = (coarsepacking / finespacking) / (1 - coarsepacking)
    with open("tempmix.csv", "w", newline="") as out_file:
        csv_writer = csv.writer(out_file)
        for x in range(48, 60 + 1):
            x /= 100
            y = factor * x / (1 - x)
            csv_writer.writerow([x, y])
    

    compared to your snippet, the key modifications are:

    • open the file outside of the loop
    • instantiate the csv.writer() outside of the loop
    • use csv_writer.writerow() to write each row at once
    • the row includes both the value from percentage_fines_agg and the value computed form it

    I also took the liberty of introducing the following non-mandatory but helpful modification:

    • removing unused variables
    • simplifying the calculations (defining a factor outside of the loop)
    • simplifying some variable names
    • generating the percentage_fines_agg values dynamically.

    If you want to use Pandas, this is much simpler to write:

    import pandas as pd
    
    
    finespacking = 0.55
    coarsepacking = 0.6
    factor = (coarsepacking / finespacking) / (1 - coarsepacking)
    df = pd.DataFrame(data=range(48, 60 + 1))
    df[0] /= 100
    df[1] = factor * df[0] / (1 - df[0])
    df.to_csv("tempmix.csv", header=False, index=False)
    

    In both cases, the content of tempmix.csv is the following:

    0.48,2.517482517482517
    0.49,2.620320855614973
    0.5,2.727272727272727
    0.51,2.8385899814471243
    0.52,2.9545454545454546
    0.53,3.0754352030947776
    0.54,3.2015810276679844
    0.55,3.3333333333333335
    0.56,3.4710743801652897
    0.57,3.6152219873150093
    0.58,3.7662337662337655
    0.59,3.9246119733924605
    0.6,4.09090909090909