[英]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()
try
和finally
的原因在這里解釋如何在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.