我正在尝试读取csv文件。在下面的代码中,没有输入for循环,也没有抛出异常:
csvfile = r"C:\Development\input-data\Locations.csv"
try:
with open(csvfile, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
#print ("row: " + str(row))
print (', '.join(row))
except IOError:
print ("IOError: " + csvFile)
sys.exit()
我做错了什么?
编辑: 错误是2部分。首先,正如@bernie建议的那样,我用我的代码覆盖了csvfile。其次,改变代码,如@KarenClark所示。
答案 0 :(得分:3)
使用open"在"中声明csv文件部分,像这样:
try:
with open(r'C:\Development\input-data\Locations.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
print (', '.join(row))
except IOError:
print ("IOError: " + csvFile)
sys.exit()
答案 1 :(得分:0)
我尝试使用for循环和if else条件读取csv文件。 看起来太大了 但它对我有用...... 试试吧。
import sys
f1 =open("csv_file.csv")
def splitter(f1):
f2 = f1.readlines()
check = 0
check1 = 0
x =""
y =""
temp=[]
for row in f2:
if row.find('"')!= -1:
for i in row:
if i == '"':
check = check+1
if (check)%2 == 0:
temp.append(x)
x=""
continue
if (check)%2 != 0:
x = x+i
continue
if i == ',':
check1= check1+1
if (check1)>= 2:
if y=="":
continue
temp.append(y)
y=""
continue
if i=='\n':
y = y+i
temp.append(y)
y=""
continue
if (check1)>=1:
y = y+i
continue
if i=="":
continue
for s in temp:
print s
temp=[]
else:
z= row.split(',')
for a in z:
print a
def main(argv):
splitter(f1)
if __name__ == "__main__":
try:
main(sys.argv)
except KeyboardInterrupt:
pass
`