【问题标题】:skipinitialspace in Python csv doens't skip tabsPython csv 中的 skipinitialspace 不会跳过制表符
【发布时间】:2023-01-31 02:53:43
【问题描述】:

我正在尝试用 Python 解析一个 csv 文件,但这些字段是使用制表符而不是空格排列的。所以我想使用 skipinitialspace=True 选项,但它不会跳过制表符(如文档所述)。所以我想出了下面的解决方案,但我想知道是否有更好的解决方案。更好的是更快,使用更少的内存或更优雅。

另外我发布这个问题是因为我正在寻找一种方法来解决这个问题但我找不到,所以这也可能对其他人有帮助。

这是我想出的:

try:
    buffer = io.StringIO()
    with open('myFile.csv', 'r') as csv_file:
        for csv_line in csv_file:
            if csv_line == '\n' or csv_line == '\r\n':   #skip empty line
                continue
            if csv_line[:1] == '#':                      #skip lines that start with # as they are commented out
                continue
            buffer.write(csv_line.replace('\t', ' '))    #replace all tabs with spaces (otherwise skipinitialspace doesn't work)
    buffer.seek(0)                                       #go back to the beginning of the buffer
    try:
        reader = csv.reader(buffer, delimiter=';', quotechar='"', skipinitialspace=True)
        for row in reader:
            row = [s.strip() for s in row]              #strip leading and trailing whitespace (tabs, spaces, ...)
            if (len(row) == 0) or (len(row[0]) == 0):   #skip empty line
                continue
            #ignore everything that starts with a #
            if row[0][:1] == '#':                       #skip lines that start with # as they are commented out
                continue
            #--- DO STUFF HERE TO PROCESS DATA ---
    except csv.Error as e:
        return (f'''CSV error: {e}''')
except UnicodeDecodeError as e:
    return (f'''Error found in CSV file. Make sure it is in UTF-8 format: {e}''')
except OSError as e:
    return ('''Error opening menu file: {e}''')

【问题讨论】:

    标签: python csv


    【解决方案1】:

    strip() 去除所有空白字符,包括制表符。所以您不需要单独清除初始选项卡或其他 的情况下 在一行的末尾......如果你要剥离每一个项目

    strip() 去除前导或尾随....空格、制表符、换行符、回车符、换页符和垂直制表符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2015-07-06
      • 2013-07-23
      相关资源
      最近更新 更多