我的'for'循环中的python语法无效

时间:2012-11-08 02:12:11

标签: python csv syntax

def citypop():
  import csv                                  
  F = open("Top5000Population.txt")           
  csvF = csv.reader(F)
  D = {}
  with csvF for row in csvF:
      city,state,population = row[0],row[1],row[2] 
      population = population.replace(',','') 
      population = int(population)
      city = city.upper()[:12]
      D[(city, state)] = population
  return D

函数citypop()返回一个以(city,state)为键的dict,以及该城市(在该状态下)的总体值作为值。

我一直收到语法错误..我不正确理解csv模块吗?

编辑:感谢帮助人....这应该可行,但现在突然间我得到了错误

 for city, state, population in reader(F):       File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode         return codecs.ascii_decode(input, self.errors[0]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa4 in position 7062: ordinal not in range(128)  

当我运行测试用例时....任何建议?

2 个答案:

答案 0 :(得分:3)

当你尝试使用with语句时,你会认为这意味着 - 在这种情况下,文件将在离开代码后立即关闭:

from csv import reader

def citypop():
  D = {}
  with open("Top5000Population.txt") as F:
    for city, state, population in reader(F):
      city = city.upper()[:12]
      D[(city, state)] = int(population.replace(',',''))
  return D

OR:

def citypop():
  with open("Top5000Population.txt") as F:
    return dict(((x.upper()[:12], y), int(z.replace(',', '')) for x, y, z in reader(F))

答案 1 :(得分:1)

我认为你误解了Python的with statement。制作第6行:

for row in csvF:

应该解决问题。

作为参考,with语句与C#中的using语句基本相同;它声明了完成后需要卸载或释放的资源范围。