Search code examples
pythoncsvheader

Skipping first line in csv.file, when it's a string, with python


I'm trying to skip the first line in a csv.file of the format:

#utm32Hetrs89_h_dvr90
667924.1719,6161062.7744,-37.15227
 667924.9051,6161063.4086,-37.15225
 667925.6408,6161064.0452,-37.15223
 667926.2119,6161064.6107,-37.15221
 667926.4881,6161065.0492,-37.15220
 667926.7642,6161065.4876,-37.15220
 667927.0403,6161065.9260,-37.15219
 667927.3164,6161066.3644,-37.15218

This is my code so far:

with open('C:\\Users\\Bruger\\Desktop\\dtu\\S\\data\\WL_geoid_values.txt',newline='') as file:
    readCSV = csv.reader(file, delimiter=',',skipinitialspace=True)
    header = next(readCSV)
    for row in readCSV:
        coordsx.append(float(row[0]))
        coordsy.append(float(row[1]))  
        h_gravs.append(float(row[2]))

I get an error saying i can't convert a string to a float. How do i make sure that it actually skips the first line before i start reading the rows?


Solution

  • I humbly suggest to use pandas to read CSV files. You can define the lines to skip and the format in a few lines:

    import pandas as pd
    
    # One single line to read all the data with the right format
    df = pd.read_csv('C:\\Users\\Bruger\\Desktop\\dtu\\S\\data\\WL_geoid_values.txt', 
                     skiprows = 1,                           # Skip first row
                     names = ['coordsx','coordsy','h_gravs'] # Rename each column
                    )
    
    # Separating each column and turning then into lists
    coordsx = df['coordsx'].tolist()
    coordsy= df['coordsy'].tolist()
    h_gravs= df['h_gravs'].tolist()