我使用的是Python 3.2.1,我不能导入StringIO模块。我使用
io。StringIO和它的工作,但我不能使用numpy的genfromtxt像这样:
x="1 3\n 4.5 8"
numpy.genfromtxt(io.StringIO(x))
我得到以下错误:
TypeError: Can't convert 'bytes' object to str implicitly
当我输入StringIO时,它会说
ImportError: No module named 'StringIO'
当我写导入StringIO时,它说没有这样的模块。
Python 3.0新增功能:
StringIO和cStringIO模块消失了。相反,导入io . xml文件
模块并使用io。StringIO或io。BytesIO用于文本和数据
分别。
.
修复一些Python 2代码,使其在Python 3中也能正常工作的一个可能有用的方法(买者自负):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
注意:这个例子可能与问题的主要问题无关,只是作为在处理缺少的StringIO模块时需要考虑的问题。对于更直接的解决方案,消息TypeError:不能隐式地将'bytes'对象转换为str,请参阅这个答案。
当我写导入StringIO时,它说没有这样的模块。
Python 3.0新增功能:
StringIO和cStringIO模块消失了。相反,导入io . xml文件
模块并使用io。StringIO或io。BytesIO用于文本和数据
分别。
.
修复一些Python 2代码,使其在Python 3中也能正常工作的一个可能有用的方法(买者自负):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
注意:这个例子可能与问题的主要问题无关,只是作为在处理缺少的StringIO模块时需要考虑的问题。对于更直接的解决方案,消息TypeError:不能隐式地将'bytes'对象转换为str,请参阅这个答案。
下面是Python 3的另一个例子。它将使用两个函数来添加两个数字,然后使用CProfile保存.prof文件。然后它将使用pstats加载保存文件。Stats和StringIO来将数据转换为字符串以供进一步使用。
main.py
import cProfile
import time
import pstats
from io import StringIO
def add_slow(a, b):
time.sleep(0.5)
return a+b
def add_fast(a, b):
return a+b
prof = cProfile.Profile()
def main_func():
arr = []
prof.enable()
for i in range(10):
if i%2==0:
arr.append(add_slow(i,i))
else:
arr.append(add_fast(i,i))
prof.disable()
#prof.print_stats(sort='time')
prof.dump_stats("main_funcs.prof")
return arr
main_func()
stream = StringIO();
stats = pstats.Stats("main_funcs.prof", stream=stream);
stats.print_stats()
stream.seek(0)
print(16*'=',"RESULTS",16*'=')
print (stream.read())
用法:
python3 main.py
输出:
================ RESULTS ================
Tue Jul 6 17:36:21 2021 main_funcs.prof
26 function calls in 2.507 seconds
Random listing order was used
ncalls tottime percall cumtime percall filename:lineno(function)
10 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
5 2.507 0.501 2.507 0.501 {built-in method time.sleep}
5 0.000 0.000 2.507 0.501 profiler.py:39(add_slow)
5 0.000 0.000 0.000 0.000 profiler.py:43(add_fast)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
注释:我们可以在上面的代码中观察到,时间。睡眠功能大约需要2.507秒。