os.path.join 抛出错误 'type of argument must be str or bytes not TextIOWrapper'
os.path.join throws error 'type of argument must be str or bytes not TextIOWrapper'
我正在尝试打开 json 文件然后从中读取(稍后也会执行相同操作并将一些 json 数据转储到同一个文件中)。
我只是想为文件名使用一个变量,所以我的代码如下所示:
layout_file = 'layouts2.json'
try:
filename = os.path.join(app.static_folder, layout_file)
with open(filename) as layout_file:
layouts = json.load(layout_file)
except:
print("could not load layouts from config file")
在我的代码看起来像这样并且运行良好之前:
try:
filename = os.path.join(app.static_folder, 'layouts2.json')
with open(filename) as layout_file:
layouts = json.load(layout_file)
except:
print("could not load layouts from config file")
我得到的错误是 error 'type of argument must be str or bytes not TextIOWrapper'
。
我现在真的不知道该怎么做,我想即使这应该可以很快解决。
提前致谢!
您正在为文件名和文件句柄使用相同的变量 layout_file
。
在编写的代码中,应该可以正常工作;但是,如果您在循环或类似的情况下执行此操作,最终可能会混淆这两个值。 (如果你用mypy
,它也会报错。)
使用不同的变量名?
layout_filename = 'layouts2.json'
try:
filename = os.path.join(app.static_folder, layout_filename)
with open(filename) as layout_fh:
layouts = json.load(layout_fh)
except:
print("could not load layouts from config file")
我正在尝试打开 json 文件然后从中读取(稍后也会执行相同操作并将一些 json 数据转储到同一个文件中)。
我只是想为文件名使用一个变量,所以我的代码如下所示:
layout_file = 'layouts2.json'
try:
filename = os.path.join(app.static_folder, layout_file)
with open(filename) as layout_file:
layouts = json.load(layout_file)
except:
print("could not load layouts from config file")
在我的代码看起来像这样并且运行良好之前:
try:
filename = os.path.join(app.static_folder, 'layouts2.json')
with open(filename) as layout_file:
layouts = json.load(layout_file)
except:
print("could not load layouts from config file")
我得到的错误是 error 'type of argument must be str or bytes not TextIOWrapper'
。
我现在真的不知道该怎么做,我想即使这应该可以很快解决。
提前致谢!
您正在为文件名和文件句柄使用相同的变量 layout_file
。
在编写的代码中,应该可以正常工作;但是,如果您在循环或类似的情况下执行此操作,最终可能会混淆这两个值。 (如果你用mypy
,它也会报错。)
使用不同的变量名?
layout_filename = 'layouts2.json'
try:
filename = os.path.join(app.static_folder, layout_filename)
with open(filename) as layout_fh:
layouts = json.load(layout_fh)
except:
print("could not load layouts from config file")