2016-01-14 204 views
0

我正在尝试读取csv文件。在下面的代码中,不会输入for循环,也不会引发异常:无法读取csv文件

csvfile = r"C:\Development\input-data\Locations.csv" 
try: 
    with open(csvfile, 'r') as csvfile: 
     reader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
     for row in reader: 
      #print ("row: " + str(row)) 
      print (', '.join(row)) 
except IOError: 
    print ("IOError: " + csvFile) 
    sys.exit() 

我在做什么错?

编辑: 错误是2部分。首先,正如@bernie所说,我用我的代码覆盖了csv文件。其次,将@KarenClark显示的代码更改。

+3

你覆盖'csvfile' ... – bernie

+0

如果CSV文件是空就会发生这种情况。 – tdelaney

+0

正如@bernie所说,您正在覆盖csvfile变量。我不确定这是行不通的,但它确实是一个“坏主意”(tm)。另外,什么是“cvsFile”。最后,请发布您的csv文件的确切格式(例如第一行或典型的行)。 –

回答

3

我没有足够的排名发表评论,所以我不得不“答案”

首先,你可以张贴整个代码段,包括进口,所以我们可以看到,如果这是个问题?

第二,如果你申报“打开方式”一节中的CSV文件,这样会发生什么:

try: 
    with open(r'C:\Development\input-data\Locations.csv', 'rb') as csvfile: 
     reader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
     for row in reader: 
      print (', '.join(row)) 
except IOError: 
    print ("IOError: " + csvFile) 
    sys.exit() 
+0

是的,我知道提到循环内的csvfile值不是Pythonic,但是目标是看看是否改变了变量的位置。另一位评论者正确地说csvfile被新变量覆盖 - 如果以上工作正常,那就证明了这一点。 –

0

我尝试使用for循环,如果其他条件来读取csv文件。 似乎太大 但它对我来说是... 试试吧。

import sys 
f1 =open("csv_file.csv") 
def splitter(f1): 
    f2 = f1.readlines() 
    check = 0 
    check1 = 0 
    x ="" 
    y ="" 
    temp=[] 
    for row in f2: 
     if row.find('"')!= -1: 
     for i in row: 
      if i == '"': 
       check = check+1 
       if (check)%2 == 0: 
        temp.append(x) 
        x="" 
       continue 
      if (check)%2 != 0: 
       x = x+i 
       continue 
      if i == ',': 
       check1= check1+1 
       if (check1)>= 2: 
        if y=="": 
         continue 
        temp.append(y) 
        y="" 
       continue 
      if i=='\n': 
       y = y+i 
       temp.append(y) 
       y="" 
       continue 
      if (check1)>=1: 
       y = y+i 
       continue 
      if i=="": 
       continue 
     for s in temp: 
      print s 
     temp=[] 
    else: 
     z= row.split(',') 
     for a in z: 
      print a 

def main(argv): 
    splitter(f1) 

if __name__ == "__main__": 
    try: 
    main(sys.argv) 
except KeyboardInterrupt: 
    pass 

`