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

本文描述了一个关于Python中使用csv模块写入CSV文件的问题。在从Python 3.5迁移至Python 2.7的过程中遇到了参数数量不匹配的错误,并通过去除多余参数解决了问题。
部署运行你感兴趣的模型镜像

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

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的时候它也不会直接抛出错误,也就没有办法定位问题。

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.9

TensorFlow-v2.9

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

由于pandas依赖有问题,现在想将以下代码中包含pandas的替换成其他方法,要求不改变原有逻辑 def download_file(resp, excelrows=None): filename = "" download_files_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'downloadfiles')) try: filename = re.search(r'filename=(.*)|filename[\*]=(.*)', resp.headers["Content-Disposition"], re.IGNORECASE).group(1).encode( "latin1").decode("utf-8").replace("?", "").replace(" ", "").replace('"', "").replace(":", "") except Exception as e: print("执行失败,ERROR,文件下载异常,文件名称为空,{0}".format(e)) if not filename: raise Exception("下载文件报错,请求头无文件名") filepath = download_files_path + os.sep + filename try: with open(filepath, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): f.write(chunk) targetFilePath = local_files_path + os.sep + filename shutil.copyfile(filepath, targetFilePath) # 判断查询得到的行数与下载列表导出excel行数是否一致,一致则通过 if excelrows is not None: if filename.endswith(".csv"): csv = pandas.read_csv(targetFilePath, encoding='utf-8') targetFilePath = local_files_path + os.sep + 'result.xlsx' csv.to_excel(targetFilePath) reader = pandas.read_excel(targetFilePath, engine='openpyxl', sheet_name=0, dtype=str) if len(reader) != excelrows: raise Exception("Excel内容行数不正确,期望:{0},实际:{1}".format(excelrows, len(reader))) except Exception as e: print("执行失败,ERROR,文件下载异常,文件名称{0},{1}".format(filename, e)) finally: return resp
10-31
PermissionError Traceback (most recent call last) Cell In[6], line 8 6 from sklearn.metrics import accuracy_score, classification_report 7 # 1. 数据加载与预处理(基于您提供的代码) ----> 8 iris_df = pd.read_excel(r'D:\yuanweihuashujuji') 9 x = iris_df.iloc[:, :4].values 10 y = iris_df.iloc[:, 4].values File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\excel\_base.py:495, in read_excel(io, sheet_name, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_parser, date_format, thousands, decimal, comment, skipfooter, storage_options, dtype_backend, engine_kwargs) 493 if not isinstance(io, ExcelFile): 494 should_close = True --> 495 io = ExcelFile( 496 io, 497 storage_options=storage_options, 498 engine=engine, 499 engine_kwargs=engine_kwargs, 500 ) 501 elif engine and engine != io.engine: 502 raise ValueError( 503 "Engine should not be specified when passing " 504 "an ExcelFile - ExcelFile already has the engine set" 505 ) File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\excel\_base.py:1550, in ExcelFile.__init__(self, path_or_buffer, engine, storage_options, engine_kwargs) 1548 ext = "xls" 1549 else: -> 1550 ext = inspect_excel_format( 1551 content_or_path=path_or_buffer, storage_options=storage_options 1552 ) 1553 if ext is None: 1554 raise ValueError( 1555 "Excel file format cannot be determined, you must specify " 1556 "an engine manually." 1557 ) File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\excel\_base.py:1402, in inspect_excel_format(content_or_path, storage_options) 1399 if isinstance(content_or_path, bytes): 1400 content_or_path = BytesIO(content_or_path) -> 1402 with get_handle( 1403 content_or_path, "rb", storage_options=storage_options, is_text=False 1404 ) as handle: 1405 stream = handle.handle 1406 stream.seek(0) File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\common.py:882, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options) 873 handle = open( 874 handle, 875 ioargs.mode, (...) 878 newline="", 879 ) 880 else: 881 # Binary mode --> 882 handle = open(handle, ioargs.mode) 883 handles.append(handle) 885 # Convert BytesIO or file objects passed with an encoding PermissionError: [Errno 13] Permission denied: 'D:\\yuanweihuashujuji' 报了这个错,怎么办
最新发布
11-15
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值