问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
import csv
class NotMatrixException(Exception):
pass
class FileExistsError(Exception):
pass
a=list()
p=0
q=0
b=list()
m=0
n=0
try:
with open ('A.csv','r') as file:
lines = csv.reader(file)
for line in lines:
a.append(line)
q=len(line)
except FileExistsError:
raise FileExistsError
print(a)
p=len(a)
print(p,q)
with open ('B.csv','r') as file:
lines = csv.reader(file)
for line in lines:
b.append(line)
n=len(line)
print(b)
m=len(b)
print(m,n)
bT=list(zip(b[0],b[1],b[2]))
print(bT)
c=list()
if q!=n:
raise 'MatrixMultiError'
for m in range(p):
d=list()
for i in range(p):
sum=0
for j in range(n):
try:
sum+=int(a[i][j])*int(bT[j][i])
except ValueError:
raise NotMatrixException
d.append(sum)
c.append(d)
print(c)
with open ('C.csv','w',newline='') as file:
writer = csv.writer(file)
writer.writerows(c)
运行结果及报错内容
G:\python\venv\Scripts\python.exe G:/python/demo.py
Traceback (most recent call last):
File "G:\python\demo.py", line 42, in
sum+=int(a[i][j])*int(bT[j][i])
ValueError: invalid literal for int() with base 10: ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "G:\python\demo.py", line 44, in
raise NotMatrixException
main.NotMatrixException
[['1', '1', '1'], ['1', '1', ''], ['1', '1', '1']]
3 3
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
3 3
[('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]
进程已结束,退出代码1
我的解答思路和尝试过的方法
我想要达到的结果
判断csv文件内容是否为矩阵,如果不是矩阵抛出异常NotMatrixException