我正在将python脚本切换到python 3,在移植一部分csv评估代码时遇到了困难。
在python 2.7.5中,这段代码运行得很好:
filename=askopenfilename()
with open(filename, 'rb') as Order:
reader = csv.reader(Order, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
OrderList = []
first = Order.next()
if (first.count("Web ID") == 1):
OrderList.append("Digi-key")
OrderList.append(first)现在,我已经将Order.next()行更改为next(Order),这样它就可以运行w/ python 3,尽管我似乎找不到与if (first.count("Web ID") == 1):等价的python3。
我已经查看了Python 3的CSV模块文档,我可能遗漏了一些东西,而且我并没有尽最大努力去找出它。
我试图回避的部分是(为了保持隐私而更改的数字):
Web ID,Access ID,Salesorder Number,Shipping Method,Payment Method,
49488634,84901,37873472,U.S. Postal Service Priority Mail* (2-3 Day Delivery to most US addresses)(order by 8:00 PM CT),Foo,
Shipping Address
...当前的错误是:
TypeError: Type str doesn't support the buffer API有什么想法吗?
发布于 2014-06-01 17:17:28
方法count是通过字符串或列表实现的。在您的示例中,您是在一个字符串上调用它,通过调用文件对象的next方法从文件对象中检索该字符串。在Python 3中,当您以二进制模式打开一个文件时,您将得到一个字节字符串的可迭代性,而不是字符串。类型bytes也实现了count,但是您只能计数字节串中出现的字节字符串,否则您将得到一个TypeError。
In [1]: b'hello'.count(b'el')
Out[1]: 1
In [2]: b'hello'.count('el')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-df699ac18654> in <module>()
----> 1 b'hello'.count('el')
TypeError: Type str doesn't support the buffer API无论如何,为了进行CSV解析,您可能必须以文本模式打开文件,因为 documentation说:
csv.reader(csvfile, dialect='excel', **fmtparams)返回一个读取器对象,它将遍历给定csvfile中的行。csvfile可以是任何支持迭代器协议并在每次调用字符串时返回__next__()方法的对象--文件对象和列表对象都是合适的。
注意我添加的"string“一词的重点。您应该按链接页面的建议,以文本模式打开文件,最好使用newline=''。
另外,您可能可以将first = next(order)更改为first = next(reader)。这样,您将有一个字符串列表(一行),并且在其中计算某个字符串的出现情况可能会更健壮。
发布于 2014-06-01 17:16:19
根据csv模块(https://docs.python.org/3.4/library/csv.html?highlight=csv#csv)的python文档,为了在Python3中翻译该方法,您应该在CSV对象上使用next()函数:
csvreader.__next__()
Return the next row of the reader’s iterable object as a list, parsed according to the current dialect. Usually you should call this as next(reader).我希望这能帮到你
干杯
发布于 2014-06-01 17:23:07
问题是在以模式=‘rb’打开文件时。我发现,如果你打开模式'r',那么它应该工作:
with open(filename, 'r') as Order:当使用'rb‘打开时,Python3将文件解释为一系列字节,并以字节的形式读取内容。使用mod 'r',Python3将文件读入字符串。
https://stackoverflow.com/questions/23982310
复制相似问题