1 -- TypeError: 'str' object is not callable
Traceback (most recent call last):
File "myfirstpython.py", line 39, in <module>
print("params list:",str(sys.argv))
TypeError: 'str' object is not callable
str()是系统的方法,不能在用它的时候,同时自定义一个叫做str的变量,这样就会引起冲突。 检查一下自己的代码是不是也有类似的错误。
2、使用seek()方法报错:“io.UnsupportedOperation: can't do nonzero cur-relative seeks”错误的原因
在使用seek()函数时,有时候会报错为 “io.UnsupportedOperation: can't do nonzero cur-relative seeks”,代码如下:
照理说,按照seek()方法的格式file.seek(offset,whence),后面的1代表从当前位置开始算起进行偏移,那又为什么报错呢?
这是因为,在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常。将 f=open("aaa.txt","r+") 改成
f = open("aaa.txt","rb") 就可以了
改正后的代码如下图:
>>> f = open("aaa.txt","rb")
>>> f.seek(3,0)
3
>>> f.seek(5,1)
8
3、解决'python -m pip install --upgrade pip' 报错问题
下包的时候提示
You are using pip version 10.0.1, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
而我按照要求运行
python -m pip install --upgrade pip
理论上按照这个命令升级是没有问题的,但是今天升级的时候遇到以下错误:
AttributeError: ‘NoneType’ object has no attribute 'bytes’
初学Python,到处查资料,发现一个新命令行可以有效解决这个问题,特此记录
easy_install -U pip
4、Python报“TypeError: a bytes-like object is required, not ‘str’ ”解决办法
今天在学习Python的时候,报了这样一个错误,我先申明一下我用的python版本是3.7。
代码如下:
import os, sys
# 打开文件
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT )
str="This is test"
# 写入字符串
os.write(fd,str)
# 关闭文件
os.close( fd )
print("关闭文件成功!!")
具体错误如下:
E:\pythonwork>python os.py
Traceback (most recent call last):
File "os.py", line 7, in <module>
os.write(fd,"This is test")
TypeError: a bytes-like object is required, not 'str'
上面最后一句话的意思是“类型错误:需要类似字节的对象,而不是字符串”。
报错原因:
在这里,python3和Python2在套接字返回值解码上有区别。
解决办法:
解决办法非常的简单,只需要用上python的bytes和str两种类型转换的函数encode()、decode()即可!
- str通过encode()方法可以编码为指定的bytes;
- 反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法;
因此:我只需要把上图中的代码改成下面的即可!
import os, sys
# 打开文件
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT )
str="This is test"
# 写入字符串
os.write(fd,str.encode())
# 关闭文件
os.close( fd )
print("关闭文件成功!!")
还有一种方法也可以实现,具体代码如下:
str = 'this is fujieace.com test'
os.write(fd,bytes(str,'UTF-8'))
5、Python报SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \xXX escape
原代码
报错原因:
解决办法:
修改后的代码如下:
执行结果如下所示:
np.array(12)
是创建了包含 12 这一个数的一个一维数组,size 是 1。
错误信息也说了:cannot reshape array of size 1 into shape (3,4)
就是说:“不能把大小为 1 的数组改变形状成 (3, 4), 也就是 3 行 4 列的一个二维数组(矩阵)”。
我代码里是这样写的:
one = np.arange(12)
就是创建从 0 到 11 这 12 个数字的一个一维数组(矩阵)。然后才能转成 3 行 4 列的二维数组(矩阵)。
7、python TypeError: unsupported operand type(s) for +: 'int' and 'str'
8、Python 之 Module Not Found Error: No module named 'openpyxl'