复制代码
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()
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)