首页 > 解决方案 > Python:我无法从函数中的标准输入解析 csv

问题描述

无法从函数中的标准输入解析 csv

您好,我在我的 Mac 上尝试使用 Pythons 的csv模块来解析通过 stdin 传递的空格分隔文件:

printf "2020-01-01 Ben 2\n2020-02-01 Jenny 4\n" | ./tmp.py

当我working在最后调用的函数运行代码时,我得到了预期的结果:

$ printf "2020-01-01 Ben 2\n2020-02-01 Jenny 4\n" | ./tmp.py
function: working
['2020-01-01', 'Ben', '2']
['2020-02-01', 'Jenny', '4']

当我使用最后not_working调用的函数运行它时,出现错误:

$ printf "2020-01-01 Ben 2\n2020-02-01 Jenny 4\n" | ./tmp.py
function: not_working
Traceback (most recent call last):
  File "./tmp.py", line 36, in <module>
    not_working() # if working() was here, it would work
  File "./tmp.py", line 27, in not_working
    print_csv(args.infile, delimiter=' ')
  File "./tmp.py", line 20, in print_csv
    reader = csv.reader(infile, delimiter)
_csv.Error: unknown dialect

not_working这是最后调用的最小示例

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import csv
import sys

parser = argparse.ArgumentParser()
parser.add_argument(
    "infile",
    nargs="?",
    type=argparse.FileType("r"),
    default=sys.stdin,
)
args = parser.parse_args()

def print_csv(infile, delimiter):
    reader = csv.reader(infile, delimiter)
    for row in reader:
        print(row)

def not_working():
    print("function: not_working")
    with args.infile:
        print_csv(args.infile, delimiter=' ')

def working():
    print("function: working")
    with args.infile:
        reader = csv.reader(args.infile, delimiter=" ")
        for row in reader:
            print(row)

not_working() # if working() was here, it would work
# working()

为什么会破?为什么我可以在函数外部解析 CSV,但不能在函数内部解析?

标签: pythonmacoscsvargparse

解决方案


您忘记在;delimiter中作为关键字参数传递 print_csv这意味着您实际上是在呼叫csv.reader(infile, dialect=delimiter),而 ' ' 是一种未知的方言(通常,这仅限于'excel''excel-tab''unix'.

请参阅有关csv.reader方法签名的文档以获取更多详细信息。


推荐阅读