I have two csv files that contain:
CSVFile1:
Data A Temp at City A Temp at City B
87.900002 275.151367 273.20108
88.300003 275.213867 273.32608
CSVFile2:
Data A Temp at City A Temp at City B
79.266687 299.566367 213.20766
97.300003 306.213867 271.47999
I want to make a new CSV file that takes the difference of column values. The result should be what changed between CSVFile 1 and CSVFile 2 and I want to see this difference in a new csv.
I have tried:
import numpy as np
with open('old.csv', 'r') as t1, open('new.csv', 'r') as t2:
fileone = t1.readlines()
filetwo = t2.readlines()
with open('update.csv', 'w') as outFile:
for line in filetwo:
if line not in fileone:
outFile.write(line)
np.savetxt(f, output,fmt="%f",delimiter=',')
f.close()
Based on what I think your code is trying to do (output all the lines in filetwo that aren't in fileone), you could use the array.count() command.
file.readlines() returns an array and so both fileone and filetwo can be used like normal arrays. If the line isn't in fileone, the count of the line will be 0, for example:
Will output:
So, in your program, you could replace:
With:
EDIT:
File handling in python is accomplished through the open() function, which takes the file and the mode to open with (
'w'
for writing (which will overwrite the file completely) or'r'
for reading). So for example:Would open the file, which can then be written to using
data.write()
. The file can then be closed when finished with usingdata.close
. All this put together gives us: