【问题标题】:os.path.join throws error 'type of argument must be str or bytes not TextIOWrapper'os.path.join 抛出错误'参数类型必须是 str 或字节不是 TextIOWrapper'
【发布时间】:2020-08-21 02:57:07
【问题描述】:

我正在尝试打开并从 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'。 我现在真的不知道该怎么做,即使这应该可以很快解决,我猜。 提前致谢!

【问题讨论】:

  • print(type(app.static_folder), app.static_folder) :)
  • 试试os.path.join(app.static_folder, layout_file)
  • 代码看起来和我一样。我认为我们在这里没有看到整个故事。
  • 感谢您的回答,现在我知道出了什么问题,这确实很愚蠢。不幸的是,将变量命名为名称的变量,就像“with open(filename) as layout_file”行中的变量一样。所以我的代码在我一开始读取文件时有效,因为 layout_file 仍然是一个字符串,但在第二次之后保存到文件中,layout_file 现在确实不再是字符串了:D
  • 你的权利 COVFEFE-19。我认为只发布用于读取文件的代码而不是之后写入文件就足够了。在那之后我才意识到,当读取一切都很好但之后写入文件时,问题开始出现

标签: python json operating-system filesystems


【解决方案1】:

您对文件名和文件句柄使用相同的变量 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")

【讨论】:

  • 感谢您的回答,我自己也发现了那个愚蠢的错误!
猜你喜欢
  • 2019-12-05
  • 2011-07-05
  • 2023-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
相关资源
最近更新 更多