问题提出
import pandas as pd
df = pd.read_csv("text.csv", sep="\t")
df.to_excel("test.xlsx")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 7: ordinal not in range(128)
解决办法
import pandas as pd
def csv2excel(fp):
df = pd.read_csv(fp, sep="\t")
cols = df.columns
## 转换每一列的编码
for e in cols:
df[e] = df[e].map(lambda x: str(x).decode("utf8").encode("raw_unicode_escape").decode(
"raw_unicode_escape"))
# 这里的 utf8 为 python 运行环境默认编码, 即 sys.getdefaultencoding()
print(e)
df.to_excel(fp.replace(".csv", ".xlsx"))
print(fp)
if name == "main":
fp = "test.csv"
csv2excel(fp)