使用python讀取CSV文件時(shí)遇到編碼問題解決方案
嘗試使用python讀取CSV文件時(shí)遇到障礙。
更新:如果只想跳過字符或錯(cuò)誤,可以打開文件,如下所示:
with open(os.path.join(directory, file), 'r', encoding="utf-8", errors="ignore") as data_file:
到目前為止,我已經(jīng)嘗試過了。
for directory, subdirectories, files in os.walk(root_dir):
for file in files:
with open(os.path.join(directory, file), 'r') as data_file:
reader = csv.reader(data_file)
for row in reader:
print (row)
我得到的錯(cuò)誤是:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to
我試過了
with open(os.path.join(directory, file), 'r', encoding="UTF-8") as data_file:
錯(cuò)誤:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 223: character maps to
現(xiàn)在,如果我只打印data_file,它說它們是cp1252編碼的,但是如果我嘗試
with open(os.path.join(directory, file), 'r', encoding="cp1252") as data_file:
我得到的錯(cuò)誤是:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to
我也嘗試了推薦的套餐。
我得到的錯(cuò)誤是:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to
我要解析的行是:
2015-11-28 22:23:58,670805374291832832,479174464,"MarkCrawford15","RT @WhatTheFFacts: The tallest man in the world was Robert Pershing Wadlow of Alton, Illinois. He was slighty over 8 feet 11 inches tall.","None
任何想法或幫助表示贊賞。
解決方案
我將使用csvkit,它使用自動(dòng)檢測(cè)適當(dāng)?shù)木幋a和解碼。例如
import csvkit reader = csvkit.reader(data_file)
正如聊天解決方案所述,
for directory, subdirectories, files in os.walk(root_dir):
for file in files:
with open(os.path.join(directory, file), 'r', encoding="utf-8") as data_file:
reader = csv.reader(data_file)
for row in reader:
data = [i.encode('ascii', 'ignore').decode('ascii') for i in row]
print (data)到此這篇關(guān)于用python讀取CSV文件時(shí)遇到編碼問題的文章就介紹到這了,更多相關(guān)python讀取CSV文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python簡(jiǎn)單幾步實(shí)現(xiàn)時(shí)間日期處理到數(shù)據(jù)文件的讀寫
這篇文章主要為大家介紹了python簡(jiǎn)單幾步實(shí)現(xiàn)時(shí)間日期處理到數(shù)據(jù)文件的讀寫詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python PyQt5中單行文本輸入控件QLineEdit用法詳解
在PyQt5的GUI編程中,QLineEdit控件是一個(gè)用于輸入和編輯單行文本的部件,它提供了豐富的功能和靈活性,可以輕松地實(shí)現(xiàn)用戶輸入的捕獲、驗(yàn)證和格式化等功能,本文將通過實(shí)際案例詳細(xì)介紹QLineEdit控件的常用方法,需要的朋友可以參考下2024-08-08
計(jì)算機(jī)二級(jí)python學(xué)習(xí)教程(1) 教大家如何學(xué)習(xí)python
這篇文章主要為大家詳細(xì)介紹了計(jì)算機(jī)二級(jí)python學(xué)習(xí)教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法詳解
這篇文章主要介紹了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法,較為詳細(xì)的分析了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的具體步驟、相關(guān)命令與操作注意事項(xiàng),需要的朋友可以參考下2019-07-07

