python3.x 讀取csv遇到的bug

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就被釋放了需要再次讀取才能讀其他的列???

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章