Search code examples
pythoncsvdatareader

How to do calculations from a csv in python


So, currently I have a csv file created with 6 rows, 1 column (header and 5 numbers) I want to be able to do a conversion, say from centimeters to inches and save it in a new csv with a new header.

I am new to coding in general, but I so far I have only been able to import the csv and read it, and print it (using print row) but I was wondering how I could do the conversion, since the numbers are saved in the csv would I have to convert the numbers to float and then somehow write it to a new csv? I only have 5 numbers as I want to be able to just figure out the correct code, but I want to be able use it for a lot of numbers and not just for 5. Therefore, I could not write print row[1] or something like that as that would take too long.

I wasn't sure where the computation would be placed either. Help please! Also, this isn't homework or the like. Im just doing this for fun.

This is the code I currently have:

import csv

with open('test.csv', 'rb') as f:
    reader = csv.reader(f)
    next(reader, None)   # I did this to skip the header I labelled Centimeters 

with open('test1.csv', 'wb') as o:
    writer = csv.writer(o)
    for row in reader


f.close()
o.close()

I guess I dont know how to convert the number in the rows to float and then output the values. I want to just be able to multiply the number in the row by 0.393701 so that in the new csv the header is labelled inches with the output beneath in the rows.


Solution

  • If the numbers are one per row it's not really a CSV file, it's just a text file in which case you don't need to use the csv reading system from Python's libraries to read it (although that library will read the file just fine as well).

    Basically, you're program will look like this (this isn't real Python code, it's your job to come up with that!):

     with either the CSV module or regular file operations
         open your file
         with either the CSV module or regular file operations
            open an output file with a different name
         for each line in the input file
            convert the value you read to float()
            transform the value 
            write the value to the output file
    

    Is that enough to get you started? (This is actually more lines than the final Python program will need since you can combine some of the lines easily into one).