在Python2.4.3中,读取.csv文件并跳过第一行的命令是什么

2024-05-23 23:43:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我学习了如何在2.7版的python中编写脚本;但是,我正在编写代码的系统现在只有2.4.3版。我试图打开一个名为输入.csv,读取第0、1、2和3列,同时跳过第一行,因为它包含我不需要的头信息。我附加的代码可以很好地与Python2.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])

Tags: csvthetocsvfile代码nameforlist
3条回答

你可以利用读卡器.下一个()

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

reader.next()

根据https://docs.python.org/release/2.4.3/lib/csv-contents.html,在调用next之前,您需要read该csv文件。而且,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的原因,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

...

相关问题 更多 >