首页 > 解决方案 > 如何使用 python 和 pandas 编写带有阿拉伯字符的 csv 文件?

问题描述

我有一个读取 csv 或 excel 文件并尝试复制和粘贴或使用 pandas 包读取和写入文件的功能。

当我尝试将带有阿拉伯字符的文件写入 csv 文件时,它会显示符号和不可理解的字符。

如何指定utf-8文件的编码并能够对其进行解码?

功能 :

import pandas as pd
import numpy as np
import base64

def download_file(df, types, new_types, extension):
    for i, col in enumerate(df.columns):
        new_type = types[new_types[i]]
        if new_type:
            try:
                df[col] = df[col].astype(new_type)
            except:
                st.write('Could not convert', col, 'to', new_types[i])
        # csv
    if extension == 'csv': 
        csv = df.to_csv(r"F:\AIenv\update2.csv",index=False,header=True,encoding="utf8")
        b64 = base64.b64encode(csv.encode()).decode("utf-8")
        
    else:
        excel = df.to_excel(r"F:\AIenv\update2.xlsx", index = False, header=True,encoding="utf-8")
        b64 = base64.b64encode(excel.encode()).decode("utf-8")
   

我在这里调用函数:

  if btn1:
    download_file(df, types, new_types, "csv")
  if btn2:
    download_file(df, types, new_types, "xls")

我的代码中的错误在哪里?

标签: pythonpandascsvencodingutf-8

解决方案


推荐阅读