使用python讀取CSV文件時遇到編碼問題解決方案
嘗試使用python讀取CSV文件時遇到障礙。
更新:如果只想跳過字符或錯誤,可以打開文件,如下所示:
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)
我得到的錯誤是:
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:
錯誤:
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:
我得到的錯誤是:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 224-225: character maps to
我也嘗試了推薦的套餐。
我得到的錯誤是:
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,它使用自動檢測適當?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)到此這篇關于用python讀取CSV文件時遇到編碼問題的文章就介紹到這了,更多相關python讀取CSV文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python簡單幾步實現(xiàn)時間日期處理到數(shù)據(jù)文件的讀寫
這篇文章主要為大家介紹了python簡單幾步實現(xiàn)時間日期處理到數(shù)據(jù)文件的讀寫詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
python PyQt5中單行文本輸入控件QLineEdit用法詳解
在PyQt5的GUI編程中,QLineEdit控件是一個用于輸入和編輯單行文本的部件,它提供了豐富的功能和靈活性,可以輕松地實現(xiàn)用戶輸入的捕獲、驗證和格式化等功能,本文將通過實際案例詳細介紹QLineEdit控件的常用方法,需要的朋友可以參考下2024-08-08
計算機二級python學習教程(1) 教大家如何學習python
這篇文章主要為大家詳細介紹了計算機二級python學習教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法詳解
這篇文章主要介紹了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法,較為詳細的分析了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的具體步驟、相關命令與操作注意事項,需要的朋友可以參考下2019-07-07

