Check that the data of a CSV file changes and print the error - Python


I have to make a file in Python that controls a file ". csv" , and if any parameter changes, indicate what value has changed, and if it matches the expected output.


When you change a column, it would be:


I would have to pass it through a code that looks up the changed value and compare it to see if the value is 0,1-1 and give a different message ( 0:Ok, 1:Pendiente, -1:ERROR ).

asked by AlberM 13.11.2016 в 12:58

1 answer


this is easier to do with the dataframes of the panda library, I'll give you an example of what I would do:

#Importamos las librerias correspondientes,
import pandas as pd
import numpy as np

# Esto lo he tenido que hacer para que lea desde una variable que sea un string, sino usar pd.from_csv(path_del_fichero)
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
    from io import StringIO
# He añadido la primera fila como nombre de columnas, para luego saber la diferencia en que columna esta

# Construimos los dos dataframes
df1 = pd.read_csv(TESTDATA, header=0)
df2 = pd.read_csv(TESTDATA2, header=0)

# Comparamos la diferencia
difference_locations = np.where(df1 != df2)
changed_from = df1.values[difference_locations]

changed_to = df2.values[difference_locations]
df = pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)

# Devolvemos un diccionario con las diferencias:

# Esto devolvería algo asi, que viene a decir que en la columna '6' pasa de(from) -1 a(to) 1.
{'from': {(0, '6'): -1}, 'to': {(0, '6'): 1}}
answered by 13.08.2017 в 13:02