python - 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,但不能在函数内部解析?
解决方案
您忘记在;delimiter
中作为关键字参数传递 print_csv
这意味着您实际上是在呼叫csv.reader(infile, dialect=delimiter)
,而 ' ' 是一种未知的方言(通常,这仅限于'excel'
、'excel-tab'
或'unix'
.
请参阅有关csv.reader
方法签名的文档以获取更多详细信息。
推荐阅读
- javascript - Axios 从 API 返回 HTML
- unity3d - 如何改变魔方的魔方将被渲染?
- scala - 从加特林 CSV 馈送器传递一个字符串数组
- java - 如何让 swing 显示/重绘自定义组件?
- c# - 在单个文件中保存和打开多个图表控件
- google-chrome - 没有 samesite 属性的 cookie 不存储在 chrome 存储中?
- python - (python 小部件)将变量分配给滑块值?
- angular - 如何使用角度材料拖放图像?
- react-native - 如何使用 AND/OR 运算符过滤列表/查询 AWS Amplify JavaScript GraphQL
- reactjs - 无法在 React 中使用 CSS 属性