我尝试用python构建数据消除代码。在这个脚本中,我尝试应用一些标准来消除数据文件,并保存新的数据文件和输入值大于0.003的输入值。为什么我在这些python脚本中得到这个错误?我将错误和脚本添加在一起。我哪一点失败了?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import csv
import itertools
import math
def main():
# ******
f = open("deneme.csv", "r")
reader = csv.reader(f)
lines = itertools.islice(reader, 3, None, 5)
n = open("results.csv", "wb")
wr = csv.writer(n, quoting = csv.QUOTE_ALL)
counter = 0
line_count = 0
for line in lines:
line_count += 5
w, h = 3, 3
matrix = [[0 for x in range(w)] for y in range(h)]
matrix[0][0] = float(line[1]) * (10 ** float(line[0]))
matrix[0][1] = float(line[11]) * (10 ** float(line[0]))
matrix[0][2] = float(line[9]) * (10 ** float(line[0]))
matrix[1][0] = float(line[11]) * (10 ** float(line[0]))
matrix[1][1] = float(line[3]) * (10 ** float(line[0]))
matrix[1][2] = float(line[7]) * (10 ** float(line[0]))
matrix[2][0] = float(line[9]) * (10 ** float(line[0]))
matrix[2][1] = float(line[7]) * (10 ** float(line[0]))
matrix[2][2] = float(line[5]) * (10 ** float(line[0]))
trace = (matrix[0][0] + matrix[1][1] + matrix[2][2]) / 3
norm = 0
for i in range(3):
for x in range(3):
norm += matrix[i][x] * matrix[i][x]
norm = math.sqrt(norm)
if (trace / norm) > 0.0003:
print(line_count - 4, line_count)
# ******
f = open("deneme.csv", "r")
reader = csv.reader(f)
rows = itertools.islice(reader, line_count - 5, line_count, None)
for i in rows:
print(i)
wr.writerow(i)
counter += 1
print(line[0])
print(matrix)
print(trace)
print(norm)
print('buyuk')
print('____________**********____________')
print(counter)
if __name__ == "__main__":
main()
对这个案例有什么建议吗?提前谢谢。我还在here错误中添加了csv文件;
Traceback (most recent call last):
File "/Users/gokceoter/PycharmProjects/CMT/cmttt.py", line 74, in <module>
21 25
['PDEW', '39083', '00:31:45.0', '1.23', '67.12', '10', '5.1', '5.4', 'CARLSBERG', 'RIDGE', '', '', '', '', '', '', '']
main()
File "/Users/gokceoter/PycharmProjects/CMT/cmttt.py", line 58, in main
wr.writerow(i)
TypeError: a bytes-like object is required, not 'str'
发布于 2018-06-05 03:48:23
您已经以二进制模式打开了输出文件
n = open("results.csv", "wb") # <---------- the `b` here
wr = csv.writer(n, quoting = csv.QUOTE_ALL)
因此写入文件时需要bytes
对象,而不是str
对象。您可以使用str.encode
和bytes.decode
在这两者之间进行转换。
for row in rows: # why would you use `i` here? Don't.
wr.writerow(row.encode())
https://stackoverflow.com/questions/50687742
复制相似问题