我已经查看了该网站的方法,但没有成功。
所以我要遍历两个csv文件,当我到达一个空字符串/单元格时会给我错误:ValueError:int()的无效文字,基数为10:''
我理解这是什么意思,但这是我尝试过的。
def normalise(students_file, units_list):
file1 = open(students_file, 'r')
data1 = file1.readline().splitlines()
file2 = open(units_list, 'r')
data2 = file2.read().splitlines()
for line in data1:
line = line.split(",")
for row in data2:
row = row.split(",")
for n in range(1, len(row), 2):
for i in range(1, len(line), 1):
if i == '':
pass
else:
print(int(line[i]) / int(row[n]))
我知道这段代码行得通,因为第一个增量的输出是0.6,这是我想要的,但是第二个增量正在尝试对空字符串进行除法,并且因为int()无法转换空字符串,因此运行错误。
任何解决方案将不胜感激。
答案 0 :(得分:0)
for i in range(1, len(line), 1):
if i == '':
if
不能为True
,因为i
将为整数。您可能是说if line[i] == '':
吗?
另一种方法是使用try
块:
try:
print(int(line[i]) / int(row[n]))
except:
# do whatever you need to do when cell is empty
# or whatever other error occurs, for example division by 0...
答案 1 :(得分:0)
就像评论说的那样。
在您的代码中,我认为可能会出现多个潜在问题。
因此,我认为您可能需要检查line[i]
和row[n]
我不确定如果它是一个空字符串,你想做什么。
但是我可以解决这个问题,并留下您的反应空间。
def normalise(students_file, units_list):
file1 = open(students_file, 'r')
data1 = file1.readline().splitlines()
file2 = open(units_list, 'r')
data2 = file2.read().splitlines()
for line in data1:
line = line.split(",")
for row in data2:
row = row.split(",")
for n in range(1, len(row), 2):
for i in range(1, len(line), 1):
#if i == '':
# i would not be '' because it comes from range()
#pass
#else:
#print(int(line[i]) / int(row[n]))
if line[i] == "" or row[n] == "":
pass
# you could do somethings likes assigning some of them as 0.
else:
print(int(line[i]) / int(row[n]))
也许它可能不是一个空字符串,也不是一个单词。
您可以使用try ...except...
def normalise(students_file, units_list):
file1 = open(students_file, 'r')
data1 = file1.readline().splitlines()
file2 = open(units_list, 'r')
data2 = file2.read().splitlines()
for line in data1:
line = line.split(",")
for row in data2:
row = row.split(",")
for n in range(1, len(row), 2):
for i in range(1, len(line), 1):
try:
print(int(line[i]) / int(row[n]))
except:
print(int(line[i]) / int(row[n]))