python的from_bytes属性,在Python中打开csv文件:内建。 AttributeError AttributeError:'_io.BytesIO'对象没有属性'file'...

本文讲述了作者在使用Python Flask框架处理CSV文件上传时遇到的问题,从错误到错误的过程,最终解决如何正确使用io.TextIOWrapper处理BytesIO对象,以避免`AttributeError`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

further to my earlier question, on how to open an csv file in Python, I am still not successful in doing so and going from error to error.

My Python code is as follows:

@app.route("/admin", methods=["GET", "POST"])

@login_required

def admin():

"""Configure Admin Screen"""

# if user reached route via POST (as by submitting a form via POST)

if request.method == "POST":

# load csv file with portfolio data

csvfile = TextIOWrapper(request.files['portfolios'].file, encoding=request.encoding)

portfolios = csv.DictReader(csvfile)

# load csv file in dictionary

for row in portfolios:

print(row['first_name'], row['last_name'])

else:

return render_template("admin.html")

My flask/html code is as follows:

{% extends "layout.html" %}

`{% block title %}

Admin

{% endblock %}

{% block main %}

Admin Console

Upload Portfolio Data

data>

Select Portfolio Upload File

Upload Security Lists

Select Security Upload File

Upload

{% endblock %}

Initially, I literally followed the example from the Python documentation:

import csv

with open('names.csv') as csvfile:

reader = csv.DictReader(csvfile)

for row in reader:

print(row['first_name'], row['last_name'])

this didnt work as it gave a type error (see my earlier post)

I then removed, as suggested, the "open", which resulted in another error. I then removed the whole with block, which again resulted in an error. Now, the above code is what I am now, and its generating the following error:

builtins.AttributeError

AttributeError: '_io.BytesIO' object has no attribute 'file'

Anyone who can help my csv import nightmare to end?? Txs!!

解决方案

io.TextIOWrapper takes a io.BytesIO object all right.

You're (almost) passing it, except that you're adding a .file (why??), which is not a field of the io.BytesIO class (request.files['portfolios'] is a io.BytesIO object already)

Just do:

csvfile = TextIOWrapper(request.files['portfolios'], encoding=request.encoding)

### 解决 `numpy.bytes_` 对象的 `AttributeError: 'bytes_' object has no attribute 'delta'` 当遇到 `numpy.bytes_` 对象没有 `delta` 属性的错误时,这通常意味着尝试访问的对象实际上是一个字节字符串而不是预期的数据结构。为了处理这种情况,可以采取以下几种方法: #### 方法一:转换数据类型 如果原始数据应该包含数值或其他可操作类型的对象而非字节串,则可能是在读取或解析过程中出现了问题。可以通过解码字节串来获取实际的内容。 ```python import numpy as np data = np.array([b'\xd0\x9f\xd1\x80', b'\xd0\xb8\xd0\xb2'], dtype=object) # 将 bytes 转换为 str 并进一步处理 decoded_data = [item.decode('utf-8') for item in data] print(decoded_data) ``` 对于特定于 `delta` 的情况,假设这是时间序列中的增量计算需求,那么应确保输入确实是日期时间格式或者其他支持此类运算的数据类型[^1]。 #### 方法二:验证并修正源代码逻辑 检查程序中创建这些 `numpy.bytes_` 实例的地方,确认是否正确加载了所需的数据文件或进行了适当的数据预处理。例如,在某些情况下可能是由于 CSV 文件列名被误解而导致的问题。 #### 方法三:自定义属性设置 如果确实需要给某个类实例动态添加新属性(尽管这不是推荐的做法),则可以在运行时通过 Python 的内置函数实现这一点。不过针对 NumPy 数组元素来说并不适用此方式解决问题。 ```python class CustomBytes(np.ndarray): @property def delta(self): raise NotImplementedError("Delta property is not implemented") custom_bytes_array = CustomBytes((2,), buffer=np.array(['a', 'b']), dtype='S') try: custom_bytes_array.delta except Exception as e: print(e) ``` 上述例子展示了如何定义一个新的子类来自定义行为,但这并不是修复原生 `numpy.bytes_` 类型的最佳实践[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值