Python 2.4.3 中读取 .csv 文件并跳过第一行的命令是什么

What are the commands to read a .csv file and skip the first row in Python 2.4.3

我在 python 2.7 版中学习了如何编写脚本;但是,我正在编写代码的系统现在只有 2.4.3 版。我试图打开一个名为 "input.csv" 的文件,读取第 0、1、2 和 3 列,同时跳过第一行,因为它包含我不需要的 header 信息。我附加的代码适用于 Python 2.7.9,但不适用于 2.4.3。有人能给我指明正确的方向,告诉我应该如何编写这段代码。

import csv          # imports the library that enables functionality to read .csv files

MATPRO_Temperature  = []  # List to hold MATPRO experimental temperatures
MATPRO_Density      = []  # List to hold MATPRO experimental densities
MATPRO_Conductivity = []  # List to hold MATPRO experimental thermal conductivities
MATPRO_References   = []  # List to hold MATPRO references for each measurement

File_Name = 'Input.csv'   # - The relative address for the MATPRO database containing
                          #   the thermal conductivity measurements

# This section opens the .csv file at the address 'File_Name' and reads in its data into lists
with open(File_Name) as csvfile:
  next(csvfile)  # This forces the reader to skip the header row of hte .csv file
  readCSV = csv.reader(csvfile, delimiter = ',')
  for row in readCSV:
    MATPRO_Temperature.append(row[0])
    MATPRO_Density.append(row[1])
    MATPRO_Conductivity.append(row[2])
    MATPRO_References.append(row[3])

根据 https://docs.python.org/release/2.4.3/lib/csv-contents.html,在调用 next 之前,您需要 read csv 文件。此外,with 关键字不在 Python 版本 2.5 之前。

 csvfile = open(File_Name, 'r') # 'r' -> read only
 try:
      readCSV = csv.reader(csvfile, delimiter = ',')
      next(readCSV) # move it here, and call next on the reader object
      for row in readCSV:
            ...
 finally:
       csvfile.close()


说明: tryfinally 的原因在此处 How to safely open/close files in python 2.4 进行了解释,但基本上,您要确保正确关闭文件(是 with 关键字的作用)即使出现错误。

另一种方法是使用 enumerate() 函数

  f = open("Input.csv")
for i, line in enumerate(f):
    if i==0:
        continue

...

你可以使用 reader.next()

reader = csv.DictReader(reading_file,fieldnames=firstline,delimiter=',')

reader.next()