文档强烈建议这是一个命令行工具,而不是在 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()
上面的一个 sn-ps 可能是你需要的,但如果你真的在寻找惩罚,你可以尝试从解释器内部使用 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()