【问题标题】:Expected str, bytes or os.PathLike object, not list when loading a python file加载 python 文件时预期的 str、bytes 或 os.PathLike 对象,未列出
【发布时间】:2021-06-16 01:53:03
【问题描述】:

这是我的代码: 导入easygui

while True:
    try:
        print('Select your file')
        proxyfile = easygui.fileopenbox('', 'Select your file')
        proxylines = proxyfile.splitlines()
        proxylinesamount = len(open(proxylines).readlines())
        break

    except (TypeError, AttributeError) as e:
        print(f'Error. File isn\'t valid. Reason: {e}')
        continue

由于某种原因,它返回以下错误:

expected str, bytes or os.PathLike object, not list

我知道这是一个 TypeError,但我就是不明白我做错了什么

【问题讨论】:

  • proxylines 是一个列表,您正尝试将其作为文件打开。
  • proxyfile.splitlines() 的目的是什么?
  • @PApostol 知道如何将其转换为字符串吗?
  • @llamaCaraDara 哎呀我忘了删除那部分。稍后在脚本中有另一个用途。
  • 看起来你想使用 len(open(proxyfile).readlines())。从我在easygui fileopenbox中阅读的内容返回文件路径

标签: python python-3.x list csv file


【解决方案1】:

我假设你想要这个:

import easygui

while True:
    try:
        print('Select your file')
        proxy_file = easygui.fileopenbox('', 'Select your file')  # Type: str
        with open(proxy_file, 'r') as fh:
            proxy_lines = list(fh)
            proxy_lines_amount = len(proxy_lines)
        break  # i'm not sure if while True and break are viable here

    except (TypeError, AttributeError) as e:
        print(f'Error. File isn\'t valid. Reason: {e}')
        continue

【讨论】:

  • 我认为list(fh) 更常见的是fh.readlines()
  • @Barmar 确定!但是我更喜欢这种方式。不要……打我……拜托?
  • 没问题,但请注意自己:)
猜你喜欢
  • 2022-08-21
  • 2018-11-08
  • 2018-11-11
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多