本文涉及CSV文件格式与UTF-8编码标准的转换和处理。
Unicode转换格式8位(UTF-8)是一种用于电子通信的可变宽度的字符编码。UTF-8可以使用1到4个字节的编码单位对超过100万个(或多或少有些奇怪)字符进行编码。UTF-8字符示例:☈,☇,★, , ,☍
UTF-8是Windows、Linux和macOS的默认编码标准。
如果你使用Python的标准文件处理操作,如open()和file.write(),编写一个CSV文件,Python将自动创建一个UTF-8文件。
因此,如果你来到这个网站搜索*"CSV to UTF-8",*我的猜测是,你读取了一个不同的编码CSV文件格式,比如ASCII、ANSI或UTF-16,其中有一些 "奇怪 "的字符。
比如,你想读取这个ANSI文件。
现在,你可以通过以下方法简单地将其转换为UTF-8 CSV文件。
在Python中进行CSV到UTF-8的转换
将CSV文件转换为CSV UTF-8文件的无库方法是以非UTF-8格式打开第一个文件,并立即将其内容写回UTF-8文件中。你可以使用 [open()](https://blog.finxter.com/python-open-function/)
函数的encoding
参数来设置要读取的文件的编码。
with open('my_file.csv', 'r', encoding='ANSI', errors='ignore') as infile:
with open('my_file_utf8.csv', 'w') as outfile:
outfile.write(infile.read())
使用给定的方法从ANSI转换到UTF-8后,新的CSV文件现在是UTF-8格式了。
CSV读/写器--CSV到UTF-8的转换
如前面的例子所示,你不需要一个CSV阅读器来将CSV转换为UTF-8。但是,如果你想这样做,请确保在打开用于创建CSV阅读器对象的文件阅读器时,传递encoding
参数。
import csv
with open('my_file.csv', 'r', encoding='ANSI', errors='ignore') as infile:
with open('my_file_utf8.csv', 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
print(row)
writer.writerow(row)
额外的newline
参数是为了防止Windows在写入每一行时增加一个额外的换行。
输出是相同的UTF-8编码的CSV。
Pandas - CSV到UTF-8的转换
你可以使用 [pandas.read_csv()](https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/)
和 [to_csv()](https://blog.finxter.com/pandas-to_csv/)
函数来读写CSV文件,使用不同的编码(如UTF-8、ASCII、ANSI、ISO),这些编码在两个函数的encoding
参数中定义。
这里有一个例子。
import pandas as pd
df = pd.read_csv('my_file.csv', encoding='ANSI')
df.to_csv('my_file_utf8.csv', encoding='utf-8', index=False)
ANSI到UTF-8
将一个ANSI编码的CSV文件转换为UTF-8编码的CSV文件的无库方法是以ANSI格式打开第一个文件,并将其内容写回UTF-8文件中。使用该 [open()](https://blog.finxter.com/python-open-function/)
函数的encoding
参数来设置要读取的文件的编码。
这里有一个例子。
with open('my_file.csv', 'r', encoding='ANSI', errors='ignore') as infile:
with open('my_file_utf8.csv', 'w') as outfile:
outfile.write(infile.read())
这就把下面的ANSI文件转换为UTF-8文件。