gpt4 book ai didi

python - 将 csv 文件转换为 dbf

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:28 27 4
gpt4 key购买 nike

我有很多 csv 文件,想将它们转换为 dbf 文件。我从 Ethan Furman 那里找到了代码(见下文)它真的很好用 - 非常感谢 - 但我的 csv 文件有一个分号作为分隔符。所以使用代码 python 将我所有的数据放入一列,但我有 5 列。如何更改分隔符?

链接在这里: Convert .csv file into .dbf using Python?

尤其是:

Using the dbf package you can get a basic csv file with code similar to this:

import dbf
some_table = dbf.from_csv(csvfile='/path/to/file.csv', to_disk=True)

This will create table with the same name and either Character or Memo fields and field names of f0, f1, f2, etc.

For a different filename use the filename parameter, and if you know your field names you can also use the field_names parameter.

some_table = dbf.from_csv(csvfile='data.csv', filename='mytable',
field_names='name age birth'.split())

Rather basic documentation is available here.

最佳答案

查看 dbf 代码,我没有看到任何传递方言的方法,因此您可以按如下方式转换文件:

import csv
reader = csv.reader(open('input.csv'), delimiter=';')
writer = csv.writer(open('output.csv', 'w'))
for row in reader:
writer.writerow(row)

注意:这将正确引用已包含逗号作为其内容一部分的行。

编辑:如果您愿意修补 dbf.from_csv 以接受 delimiter 作为参数以避免转换所有 csv 文件,这应该可行:

--- dbf.py.orig 2012-01-23 12:48:32.112101218 +0100
+++ dbf.py 2012-01-23 12:49:59.468534408 +0100
@@ -4502,13 +4502,14 @@
print str(table[0])
finally:
table.close()
-def from_csv(csvfile, to_disk=False, filename=None, field_names=None, extra_fields=None, dbf_type='db3', memo_size=64, min_field_size=1):
+def from_csv(csvfile, to_disk=False, filename=None, field_names=None, extra_fields=None, dbf_type='db3', memo_size=64, min_field_size=1,
+ delimiter=','):
"""creates a Character table from a csv file
to_disk will create a table with the same name
filename will be used if provided
field_names default to f0, f1, f2, etc, unless specified (list)
extra_fields can be used to add additional fields -- should be normal field specifiers (list)"""
- reader = csv.reader(open(csvfile))
+ reader = csv.reader(open(csvfile), delimiter=delimiter)
if field_names:
field_names = ['%s M' % fn for fn in field_names]
else:

关于python - 将 csv 文件转换为 dbf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com