【问题标题】:What is the best place to catch errors when reading files in python?在 python 中读取文件时捕获错误的最佳位置是什么?
【发布时间】:2018-10-15 14:25:55
【问题描述】:

我是 Python 新手,遇到以下问题。用户上传 CSV 文件,然后我对其进行解析。但是,很多事情都可能出错。我发现的主要问题是 a) 他们上传的文件毕竟不是 CSV 文件,或者 b) 文件不是使用 UTF8 编码(这是我们系统的默认编码)上传的。

问题是:我应该在哪里检查这些问题?这是我的脚本:

with open(path) as f:
    reader = csv.reader(f)
    for row in reader:

        (do stuff...)

我试过添加这个:

try:
    reader = csv.reader(f)
except:
    error = "There was an error..."

但如果用户上传的文件编码错误,则不会被捕获。它似乎只在循环开始时被捕获(对于读取器中的行),并且只针对导致麻烦的特定行。这是否意味着我应该在 for 语句中进行这种错误检查?对我来说只做一次似乎要好得多,而不是每件,但我不确定这里最有意义的是什么......

【问题讨论】:

标签: python csv error-handling


【解决方案1】:

使用 CSV 阅读器可能有更直接的方法来捕获这些东西(我不确定),但是当我有来自其他用户的输入文件时,我只是解析这些文件手动。例如:

import sys
NumFields = 3
inf = open(path, "rU")

for line in inf:
    line = line.strip() #get rid of weird end-of-line characters from bad encoding
    ls = line.split(",")
    if len(ls) != NumFields:
         ls = line.split("\t") ##if you can't get the number of fields with comma split, try tab
         if len(ls) != NumFields:
             sys.exit(1)
    print ls

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2020-06-20
    • 2013-08-29
    • 2023-03-25
    相关资源
    最近更新 更多