简体   繁体   中英

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

I learned how to script in python with version 2.7; however, the system I am coding on now only has version 2.4.3. I am trying to open a file titled "input.csv", read columns 0, 1, 2 and 3, while simultaneously skipping the first row since it contains header information that I do not want. The code I am attaching works fine with Python 2.7.9, but does not work with 2.4.3. Can someone point me in the right direction as to how this block of code should be written.

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

According to https://docs.python.org/release/2.4.3/lib/csv-contents.html , you need to read the csv file before calling next on it. Also, the with keyword isn't in Python till version 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()


The reason for try and finally is explained here How to safely open/close files in python 2.4 , but basically, you want to make sure you close the file properly (which is what the with keyword does) even if there is an error. tryfinally的原因在这里解释如何在python 2.4中安全地打开/关闭文件 ,但基本上,你想确保正确关闭文件(这是with关键字的作用),即使出现错误。

Another way would be to use the enumerate() function

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

...

You could use reader.next()

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

reader.next()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM