databuffer += data_str TypeError: can only concatenate str (not "_io.TextIOWrapper") to str

databuffer += data_str TypeError: can only concatenate str (not "_io.TextIOWrapper") to str

我正在尝试为来自 LIDAR 传感器的数据制作动画,但我在尝试为它制作动画时遇到了这个错误!能否帮助解决这个问题,我是Python编程的新手,非常感谢!

这是我遇到的问题:

File "C:\Users\cemal\AppData\Local\Programs\Python\Python37-32\veritipleriogrenme.py", line 29, in animate databuffer += data_str TypeError: can only concatenate str (not "_io.TextIOWrapper") to str

这些是我尝试制作动画的数据集:

0.0,0.0
0.0,269.1
0.0,270.3
0.0,271.5
1617.8,265.6
1627.3,266.8
1629.0,268.0
1633.0,269.2

我的数据集类型是字符串!


import matplotlib.pyplot as plot
import math
from matplotlib import style
import matplotlib.animation as animation 
import numpy as np
fig=plot.figure(figsize=(4,4))
ax = fig.add_subplot(111, projection='polar')
ax.set_ylim(0,2000)
data = np.zeros(360)
theta = np.linspace(0,360, num=360)
l,  = ax.plot([],[])

databuffer = ""
uzaklik = np.zeros(360)
pol = np.linspace(0,360, num=360)
def animate(i):
    global data, databuffer
    data_str = open(r"C:\Users\cemal\OneDrive\Masaüstü\veri2.txt","r")
    databuffer +=  data_str
    aci=np.linspace(0,360, num=360)
    cap=np.zeros(360)
    p_pol=np.linspace(0,360, num=360)
    p_uzaklik=np.zeros(360)
    aci2=np.linspace(0,360, num=360)
    cap=np.zeros(360)
    for x in data_str:
        pol =x.partition(",")[2].rstrip()
        uzaklik =x.split(',')[0]
        try:

            p_pol=float(pol.strip().strip("'"))
            p_uzaklik=float(uzaklik.strip().strip("'"))

            aci=np.append(p_pol)
            cap=np.append(p_uzaklik)
            aci2=[math.radians(i) for i in aci]
            l.set_data(cap, aci2 )
            data_buffer=""

            return l, 

        except ValueError:
            continue

ani = animation.FuncAnimation(fig, animate,interval=10000)
plot.show()

open 创建一个 缓冲 ​​reader。缓冲的 reader 有很多种;在本例中,它是缓冲的文本 reader。 reader 本身不能像字符串一样对待,但是,如果您告诉代码读取内容,您将获得等同于缓冲 reader 的数据类型(来自 BytesIO 缓冲的字节 reader,以及来自 TextIOWrapper 的字符串)

我会阅读一些关于缓冲 readers 的内容,因为它肯定会派上用场,here

此代码还演示了如何根据您的目的使用缓冲的 reader(对变量名称进行一些更改以更好地匹配变量类型):

data_buffer = ""
data_str_wrapper = open(r"C:\Users\cemal\OneDrive\Masaüstü\veri2.txt","r")
try:
    str += data_str_wrapper
except Exception as e:
    print("Can't combine strings and wrappers")
    print(e)
data_buffer += data_str_wrapper.read()
print("Now that i've read the buffer, I can treat it like a string")
print(data_buffer)

本质上,您需要 data_buffer 添加包装内容的 read 版本,所以在您有 databuffer += data_str 的地方,您真的应该这样做databuffer += data_str.read()