繁体   English   中英

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

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

我学会了如何使用2.7版本在Python中编写脚本; 但是,我现在编写的系统只有版本2.4.3。 我正在尝试打开一个名为“input.csv”的文件,读取第0,1,2和0列,同时跳过第一行,因为它包含我不想要的标题信息。 我附加的代码适用于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 ,你需要read之前调用csv文件next就可以了。 此外, with关键字在版本2.5之前不在Python中。

 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的原因在这里解释如何在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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