Python - CSV读作一大行

时间:2013-10-04 08:57:38

标签: python csv readlines

我是Python的新手,我正在从一个教程中学习,这里有一行,假设从.csv文件中读取并跳过第一行(标题):

data = open("banklist.csv", "r").readlines()[1:]
for entry in data:
  #do some stuffs

问题是,它甚至没有进入循环。删除open语句中的[1:]并添加打印数据,我发现csv似乎被读作一个大行,而删除标题则删除了所有内容:

["First National Bank also operating as The National Bank of El Paso,Edinburg,TX,14318,13-Sep-13,18-Sep-13\rThe Community's Bank,Bridgeport,CT,57041,13-Sep-13,17-Sep-13\rSunrise Bank of Arizona,Phoenix,AZ,34707,23-Aug-13,11-Sep-13\rCommunity South Bank,Parsons,TN,19849,23-Aug-13,5-Sep-13\rBank of Wausau,Wausau,WI,35016,9-Aug-13,4-Sep-13\rFirst Community Bank of Southwest Florida (also operating as Community Bank of Cape Coral),Fort Myers,FL,34943,2-Aug-13,26-Aug-13\rMountain National Bank,Sevierville,TN,34789,7-Jun-13,26-Aug-13\r1st Commerce Bank,North Las Vegas,NV,58358,6-Jun-13,26-Aug-13\rBanks of Wisconsin d/b/a Bank of Kenosha,Kenosha,WI,35386,31-May-13,12-Jul-13\rCentral Arizona Bank,Scottsdale,AZ,34527,14-May-13,26-Aug-13\rSunrise Bank,Valdosta,GA,58185,10-May-13,12-Jul-13\rPisgah Community Bank,Asheville,NC,58701,10-May-13,26-Aug-13\rDouglas County Bank,Douglasville,GA,21649,26-Apr-13,26-Aug-13\rParkway Bank,Lenoir,NC,57158,26-Apr-13,26-Aug-13\rChipola Community Bank,Marianna,FL,58034,19-Apr-13,12-Jul-13\rHeritage Bank of North Florida,Orange Park,FL,26680,19-Apr-13,26-Aug-13\rFirst Federal Bank,Lexington,KY,29594,19-Apr-13,12-Jul-13"]

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您正在阅读使用系统中不同换行约定的文本文件; \r您的系统可能需要\n\r\n

您可以使用通用换行支持而不是'rU'模式打开文件:

data = open("banklist.csv", "rU").readlines()[1:]

跳过第一行的更聪明的方法是使用该文件作为迭代器;直接循环它。 next()方法允许您一次抓取一行,为您提供跳过第一行的方法:

with open("banklist.csv", "rU") as infile:
    next(infile, None)  # skip the first line
    for line in infile:
        print line 

但是,如果是CSV文件,请使用csv模块读取数据:

import csv

with open("banklist.csv", "rU") as infile:
    reader = csv.reader(infile)
    next(reader, None)  # skip the first row
    for row in reader:
        print row

CSV模块处理将行拆分为列表:

['First National Bank also operating as The National Bank of El Paso', 'Edinburg', 'TX', '14318', '13-Sep-13', '18-Sep-13']
["The Community's Bank", 'Bridgeport', 'CT', '57041', '13-Sep-13', '17-Sep-13']
['Sunrise Bank of Arizona', 'Phoenix', 'AZ', '34707', '23-Aug-13', '11-Sep-13']
['Community South Bank', 'Parsons', 'TN', '19849', '23-Aug-13', '5-Sep-13']
['Bank of Wausau', 'Wausau', 'WI', '35016', '9-Aug-13', '4-Sep-13']
['First Community Bank of Southwest Florida (also operating as Community Bank of Cape Coral)', 'Fort Myers', 'FL', '34943', '2-Aug-13', '26-Aug-13']
# etc.