报错
Traceback (most recent call last):
File "/workspace/PythonProject/main.py", line 7, in <module>
with dbfread.DBF(dbf_path, encoding='gbk') as table:
File "/usr/local/lib/python3.10/site-packages/dbfread/dbf.py", line 121, in __init__
self._read_header(infile)
File "/usr/local/lib/python3.10/site-packages/dbfread/dbf.py", line 206, in _read_header
self.header = DBFHeader.read(infile)
File "/usr/local/lib/python3.10/site-packages/dbfread/struct_parser.py", line 41, in read
return self.unpack(file.read(self.struct.size))
File "/usr/local/lib/python3.10/site-packages/dbfread/struct_parser.py", line 36, in unpack
items = zip(self.names, self.struct.unpack(data))
struct.error: unpack requires a buffer of 32 bytes
代码
import dbfread
import pandas as pd
dbf_path = r'1.DBF' # 文件所在位置
csv_filename = r"{}.csv".format(dbf_path.split(r'\\')[-1].split('.')[0]) # 输出路径
# 读取DBF文件并转换为DataFrame
with dbfread.DBF(dbf_path, encoding='gbk') as table:
records = [record for record in table]
df = pd.DataFrame(records)
new_column = pd.Series(list(map(lambda x: x + 1, df.index.tolist()))) # df.index.tolist()元素自加1
df.insert(0, '序号', new_column)
# 保存为CSV文件
df.to_csv(csv_filename, index=False, encoding='gbk')