Python TypeError:需要类似字节的对象,而不是';str';尝试写入csv文件时
我必须将以下用Python 2编写的代码转换为Python 3:Python TypeError:需要类似字节的对象,而不是';str';尝试写入csv文件时,python,python-3.x,csv,python-2.x,Python,Python 3.x,Csv,Python 2.x,我必须将以下用Python 2编写的代码转换为Python 3: with open('C:/path_to_csv_file/fold1_1.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for row, timeseq in izip(fold1, fold1_t): spamwr
with open('C:/path_to_csv_file/fold1_1.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in izip(fold1, fold1_t):
spamwriter.writerow([unicode(s).encode("utf-8") +'#{}'.format(t) for s, t in izip(row, timeseq)])
我的Python 3代码如下所示:
with open('C:/Users/path_to_csv_file/fold1_1.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in zip(fold1, fold1_t):
for s, t in zip(row, timeseq):
bytes_var = s.encode('utf-8') +'#{}'.format(t).encode('utf-8')
spamwriter.writerow(bytes_var)
fold1包含:
fold1 = ['¢©§','¢©§','¢©§']
fold1_t =[[0, 15, 173999],[0, 457325, 306],[0, 62954, 432]]
以下内容包括:
fold1 = ['¢©§','¢©§','¢©§']
fold1_t =[[0, 15, 173999],[0, 457325, 306],[0, 62954, 432]]
当我尝试执行上面的代码时,我得到以下错误:
TypeError: a bytes-like object is required, not 'str'
变量bytes_var是字节的类型,因此通常应该可以工作。
我是否在从Python2到Python3的转换过程中犯了错误,从而导致了这个错误?
谢谢。您需要将
wb
更改为w
。此外,在Python3中,可以通过直接将表达式传递到字符串的大括号中来执行格式化字符串,因此
s.encode('utf-8') +'#{}'.format(t).encode('utf-8')
可能是
f'{s}#{t}'.encode('utf-8')
总共:
import csv
fold1 = ['¢©§','¢©§','¢©§']
fold1_t =[[0, 15, 173999], [0, 457325, 306], [0, 62954, 432]]
with open('C:/path_to_csv_file/fold1_1.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in zip(fold1, fold1_t):
for s, t in zip(row, timeseq):
bytes_var = s.encode('utf-8') + f'#{t}'.encode('utf-8')
spamwriter.writerow(bytes_var)
csv
模块是Python2->Python3转换并不直接的模块之一。底层文件应以文本形式打开,不再是二进制文件,而是以空行结尾
所以我会写:
with open('C:/path_to_csv_file/fold1_1.csv', 'w', newline='', encoding='utf-8') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in izip(fold1, fold1_t):
spamwriter.writerow([s +'#{}'.format(t) for s, t in izip(row, timeseq)])
当前错误是由csv模块发送unicode字符串引起的,而不存在的文件需要字节。引发异常的行是哪行?@spoonmiser At:spamwriter.writerow(bytes\u var)感谢您的回复。代码就是这样执行的,但是“w”和“wb”没有什么不同?@C96你是什么意思?如果我错了,请纠正我,但是如果我用“wb”而不是“w”以二进制模式打开文件,文件将不会包含不同的信息?@C96你能告诉我当你运行python 2代码时文件将包含什么吗?例如,这是fold1_1b'\xc2\xa2#0'的第一行,b'\xc2\xa9#15',b'\xc2\xa7#173999'