with open(filePath,'wb',encoding='utf-8',newline='') as f:在服务器上写入文件报错

在网上寻找答案一直没有找到,我写入文件的代码是这样的:

def writeList2CSV(myList1,filePath):
    try:
        with open(filePath,'w',encoding='utf-8',newline='') as f:
            writer=csv.writer(f)
            for items in myList1:
                for item in items:
                    writer.writerow(item)
    except Exception :
        print("数据写入失败,请检查文件路径及文件编码是否正确")

这个是在python3.5的环境下写的,在服务器上运行的时候try里运行到with open就不走了,直接跑到exception里。

后来去掉try让它自动报错,发现是参数个数问题,服务器是在python2.7环境下,with open()这方法只允许给3个参数,而我给了4个,结果就不运行那句,后来去掉后面俩参数就好了。


教训就是:写程序的时候也不能总用try,这样debug的时候它也不会直接抛出错误,也就没有办法定位问题。

你可能感兴趣的:(with open(filePath,'wb',encoding='utf-8',newline='') as f:在服务器上写入文件报错)