【问题标题】:how to avoid error "no such file" and upgrade code如何避免错误“没有这样的文件”和升级代码
【发布时间】:2020-05-25 14:29:44
【问题描述】:

我尝试这样做:

jsons = [json.load(open(f'this_folder/{folder}/data.json')) for folder in os.listdir('this_ folder')]

但不是 this_folder 中的所有文件夹都包含 data.json,我得到错误:

FileNotFoundError: [Errno 2] 没有这样的文件或目录:'this_folder/3634575b59e/data.json'

如何避免或忽略此消息? 谢谢!!!

【问题讨论】:

  • 这个问题与pandas 没有任何关系。那为什么要打标签呢?

标签: python json pandas path


【解决方案1】:

您可以像这样使用try...except 表示法:

jsons = []
for folder in os.listdir('this_ folder'):
    try:
        jsons.append(json.load(open(f'this_folder/{folder}/data.json'))
    except FileNotFoundError:
        pass

但我真的建议在打开文件后关闭它们:

jsons = []
for folder in os.listdir('this_ folder'):
    try:
        json_file = open(f'this_folder/{folder}/data.json')
        jsons.append(json.load(json_file)
        json_file.close()
    except FileNotFoundError:
        pass

【讨论】:

  • 关闭文件是个好主意,但我会为此使用with 语句。 with open(f'this_folder/{folder}/data.json') as json_file:。然后会自动关闭文件。
  • 是的,你是对的......你也可以使用with声明
【解决方案2】:

正如 Anwarvic 的回答所指出的,这里要使用 try-except 语句。但出于显而易见的原因,您也应该关闭文件。您可以使用以下代码来做到这一点:

jsons = []
for folder in os.listdir('this_ folder'):
try:
    with open(f'this_folder/{folder}/data.json') as json_file:jsons.append(json.load(json_file))
except FileNotFoundError:
    pass

【讨论】:

    【解决方案3】:

    也许你可以使用 try catch 块:

    jsons = []
    for folder in os.listdir('this_ folder'):
        try:
            jsons.append(json.load(open(f'this_folder/{folder}/data.json'))
        except:
            #Do nothing
    

    对不起,这不是一个班轮。

    【讨论】:

    • Python 没有关键字catch。你的意思可能是try.. except
    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2013-04-06
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    相关资源
    最近更新 更多