我希望使用csvkit作为库,而不是从命令行将给定的excel文件转换为csv。我无法找到有关库使用语法的任何信息。任何人都可以阐明如何将csvkit用作图书馆用于此目的吗?
我的测试用例很简单 - 输入input.xlsx或input.xls,转换并保存为output.csv。这是我迄今为止所尝试的内容,它基于其他地方的建议:
import csvkit
with open('input.xlsx') as csvfile:
reader = in2csv(csvfile)
# below is just to test whether the file could be accessed
for row in reader:
print(row)
给出
Traceback (most recent call last):
File "excelconvert.py", line 6, in <module>
reader = in2csv(csvfile)
NameError: name 'in2csv' is not defined
还有一个类似的问题here,但答案似乎只是参考文档,它们既不是或者没有实际解释库使用语法,它只列出了类。有一个答案表明语法可能类似于csv模块,这是我上面尝试进行的尝试,但是我无处可去。
答案 0 :(得分:2)
文档强烈建议这是一个命令行工具,不能在Python解释器中使用。你可以这样做,从命令行将文件转换为csv(或者你可以在shell脚本中弹出它):
in2csv your_file.xlsx > your_new_file.csv
如果您想阅读该文件,只需执行此操作(它与您所拥有的类似,但您不需要任何外部模块,只需使用内置Python):
with open('input.xlsx') as csvfile:
reader = csvfile.readlines() # This was the only line of your code I changed
# below is just to test whether the file could be accessed
for row in reader:
print(row)
或者您可以使用os
模块调用命令行:
# Careful, raw sys call. Use subprocess.Popen
# if you need to accept untrusted user input here
os.popen("in2csv your_file.xlsx > your_new_file.csv").read()
上面的一个片段可能就是你需要的,但是如果你真的在寻找惩罚,你可以尝试使用解释器里面的in2csv
文件。以下是你可能会这样做的事情(在我能找到的文档中没有对此的支持,这只是我在翻译中探讨):
>>> from csvkit import in2csv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name in2csv
>>> import csvkit
>>> help(csvkit)
Help on package csvkit:
NAME
csvkit
FILE
c:\python27\lib\site-packages\csvkit\__init__.py
DESCRIPTION
This module contains csvkit's superpowered alternative to the standard Python
CSV reader and writer. It can be used as a drop-in replacement for the standard
module.
.. warn::
Since version 1.0 csvkit relies on `agate <http://agate.rtfd.org>`_'s
CSV reader and writer. This module is supported for legacy purposes only and you
should migrate to using agate.
PACKAGE CONTENTS
cleanup
cli
convert (package)
exceptions
grep
utilities (package)
因此,您无法直接从csvkit导入in2csv(因为它未列在PACKAGE CONTENTS
下)。但是,如果你进行一些狩猎,你会发现你可以从csvkit.utilities
访问该软件包。但这只会从这里变得更糟。如果你像上面那样做更多的“帮助搜索”(即从解释器调用帮助),你会发现该类被设计为从命令行使用。因此,从解释器内部使用它是一个真正的痛苦。以下是尝试使用默认值(导致爆炸)的示例:
>>> from csvkit.utilities import in2csv
>>> i = in2csv.In2CSV()
>>> i.main()
usage: [-h] [-d DELIMITER] [-t] [-q QUOTECHAR] [-u {0,1,2,3}] [-b]
[-p ESCAPECHAR] [-z FIELD_SIZE_LIMIT] [-e ENCODING] [-S] [-H] [-v]
[-l] [--zero] [-f FILETYPE] [-s SCHEMA] [-k KEY] [--sheet SHEET]
[-y SNIFF_LIMIT] [--no-inference]
[FILE]
: error: You must specify a format when providing data via STDIN (pipe).
看一下in2csv.py模块,你必须修补args
以使它在解释器中做你想做的事。同样,这不是设计用于解释器内部,它设计为从cmd行调用(因此如果从cmd行调用它,则定义args
)。这样的东西似乎运行,但我没有彻底测试它:
>>> from csvkit.utilities import in2csv
>>> i = in2csv.In2CSV()
>>> from collections import namedtuple
>>> i.args = namedtuple("patched_args", "input_path filetype no_inference")
>>> i.args.input_path = "/path/to/your/file.xlsx"
>>> i.args.no_inference = True
>>> i.args.filetype = None
>>> i.main()