首页 > 解决方案 > 跳过csv.file中的第一行,当它是一个字符串时,使用python

问题描述

我试图跳过格式的 csv.file 中的第一行:

#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

到目前为止,这是我的代码:

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]))

我收到一条错误消息,说我无法将字符串转换为浮点数。在我开始阅读行之前,如何确保它实际上跳过了第一行?

标签: pythoncsvheader

解决方案


我谦虚地建议使用pandas读取 CSV 文件。您可以在几行中定义要跳过的行和格式:

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()

推荐阅读