设为首页 收藏本站
查看: 1779|回复: 0

[经验分享] python3.x 读取csv遇到的bug

[复制链接]

尚未签到

发表于 2018-8-9 12:59:53 | 显示全部楼层 |阅读模式
  1、failed to set main.loader
  

兴奋地配置好了Python环境,运行hello.py实例就出现这个异常,着实让人扫兴,百度上搜了下没有找到答案。再去Google了下,发现可能是hello.py文件中包含非英文字符,果然将hello.py放到纯英文路径下就没问题了。  

  
对于eclipse下使用PyDev的情况,可以用File->Switch Workspace的方法来切换到一个英文路径工作空间目录
  

  2、_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
  

在用下面的代码处理csv文件时出现这个错误(Python 3)  

  复制代码
  import csv
  def main():
  reader=csv.reader(open('userid.csv', 'rb'))
  for item in reader:
  print(item)
  if name == 'main':
  main()
  复制代码
  

经过万能的Google搜索,找到了问题所在:http://bugs.python.org/msg82661 ,下面是部分摘录:  

  复制代码
  Sorry, folks, we've got an understanding problem here. CSV files are
  typically NOT created by text editors. They are created e.g. by "save as
  csv" from a spreadsheet program, or as an output option by some database
  query program. They can have just about any character in a field,
  including \r and \n. Fields containing those characters should be quoted
  (just like a comma) by the csv file producer. A csv reader should be
  capable of reproducing the original field division. Here for example is
  a dump of a little file I just created using Excel 2003:
  ...
  This sentence in the documentation is NOT an error: """If csvfile is a
  file object, it must be opened with the ‘b’ flag on platforms where that
  makes a difference."""
  复制代码
  虽然这个解释没有告诉我们怎么解决这个问题,但是我根据上面这段话,将代码改成下面这样就OK了:
  复制代码
  import csv
  def main():
  reader=csv.reader(open('userid.csv', 'r'))
  for item in reader:
  print(item)
  if name == 'main':
  main()
  复制代码
  3、UnboundLocalError: local variable 'f' referenced before assignment(f.close())
  

代码如下:  

  复制代码
  

# Errors and Exceptions  
# 详细文档参考:http://docs.python.org/2/tutorial/errors.html
  
try:
  f = codecs.open("noexistfile.txt", "rU", "utf-8")
  text = f.read()
  
except Exception:
  sys.stderr.write('读取文件发生IO异常!\n')
  
finally:
  f.close()
  sys.stderr.write('finnaly执行!\n')
  

  复制代码
  这个错误在打开的文件不存在时才会发生。原因是如果文件不存在则f是None,这时在except语句分支中执行f.close()会报一样的错。这与Java里的文件读取异常处理不太一样,正确的做法如下:
  复制代码

Errors and Exceptions
  

# 详细文档参考:http://docs.python.org/2/tutorial/errors.html  
try:
  f = codecs.open("noexistfile.txt", "rU", "utf-8")
  text = f.read()
  f.close()
  
except Exception:
  sys.stderr.write('读取文件发生IO异常!\n')
  
finally:
  sys.stderr.write('finnaly执行!\n')
  

  复制代码
  

其他可能的一种情况:http://blog.csdn.net/magictong/article/details/4464024  

  
文件读写的推荐写法如下(这样不需要显式关闭文件):
  

  with open("test.txt", "r") as file_handle:
  for line in file_handle:

...
  4
  [python] view plain copy
  

import numpy as np  
import csv
  
with open ("E:/6Machine Learning/Deep learning/ML2017/hw1.1/hw1/data/train.csv", "r") as csvfile:
  read = csv.DictReader(csvfile)
  price = [row["price"] for row in read]
  a = len(price)
  
with open("E:/6Machine Learning/Deep learning/ML2017/hw1.1/hw1/data/train.csv", "r") as csvfile:
  read = csv.DictReader(csvfile)
  sqft_living=[row["sqft_living"] for row in read]
  b=len(sqft_living)
  

  read 完这个file以后file就被释放了需要再次读取才能读其他的列???

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-549205-1-1.html 上篇帖子: Python自学起飞——003 下篇帖子: Nginx+uwsgi+Django (Python web环境)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表