Python使用编码类型转换为CSV

vaqhlq81  于 2023-01-28  发布在  Python
关注(0)|答案(1)|浏览(139)

有人帮我一个程序,这样我就可以将PDF文件从该格式转换为csv,但他们没有指定编码类型,下面是代码:

import os
import glob
import tabula

path="/Users/username/Downloads/"
for filepath in glob.glob(path+'*.pdf'):
    name=os.path.basename(filepath)
    tabula.convert_into(input_path=filepath, 
                        output_path=path+name+".csv",
                        pages="all")

如何获得要转换为utf-8cp1252编码的CSV文件
谢谢你帮忙
我得到的错误

hwazgwia

hwazgwia1#

您可以使用chardet库获取tabula生成的文件的结果编码,然后使用pandas将其转换为您想要的编码。

import chardet
import pandas as pd

for filepath in glob.glob(path+'name.csv'):
    with open(filepath, 'rb') as f:
        result = chardet.detect(f.read())
    df = pd.read_csv(filepath,encoding=result['encoding'])
    df.to_csv(filepath,index=False,encoding='utf-8')

相关问题