(2022-01-06) Python學(xué)習(xí)筆記

〇〇一:??

2022.1.6? 13:30

在linux下用慣了, 換到windows下,會有種種想不到的問題.比如昨天碰到的用read_csv讀取文件報錯,實際上是路徑書寫的問題.

錯誤信息一大堆:

---------------------------------------------------------------------------------------

---------------------------------------------------------------------------OSErrorTraceback (most recent call last)E:\Temp/ipykernel_2916/1776550767.pyin<module> 1importpandasaspd 2# 讀取練習(xí)數(shù)據(jù)弦赖,文件路徑為'./工作/test_data.csv',編碼格式為'utf-8'----> 3 test_data=pd.read_csv('E:\Downloads\課程素材\工作\test_data.csv',encoding='utf-8') 4# 查看 test_data 5test_datad:\program files\python37\lib\site-packages\pandas\util\_decorators.pyinwrapper(*args, **kwargs) 309stacklevel=stacklevel, 310)--> 311 returnfunc(*args,**kwargs) 312 313returnwrapperd:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyinread_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options) 584kwds.update(kwds_defaults) 585--> 586 return_read(filepath_or_buffer,kwds) 587 588d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin_read(filepath_or_buffer, kwds) 480 481# Create the parser.--> 482 parser=TextFileReader(filepath_or_buffer,**kwds) 483 484ifchunksizeoriterator:d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin__init__(self, f, engine, **kwds) 809self.options["has_index_names"]=kwds["has_index_names"] 810--> 811 self._engine=self._make_engine(self.engine) 812 813defclose(self):d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin_make_engine(self, engine) 1038) 1039# error: Too many arguments for "ParserBase"-> 1040 returnmapping[engine](self.f,**self.options)# type: ignore[call-arg] 1041 1042def_failover_to_python(self):d:\program files\python37\lib\site-packages\pandas\io\parsers\c_parser_wrapper.pyin__init__(self, src, **kwds) 49 50# open handles---> 51 self._open_handles(src,kwds) 52assertself.handlesisnotNone 53d:\program files\python37\lib\site-packages\pandas\io\parsers\base_parser.pyin_open_handles(self, src, kwds) 227memory_map=kwds.get("memory_map",False), 228storage_options=kwds.get("storage_options",None),--> 229 errors=kwds.get("encoding_errors","strict"), 230) 231d:\program files\python37\lib\site-packages\pandas\io\common.pyinget_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options) 705encoding=ioargs.encoding, 706errors=errors,--> 707 newline="", 708) 709else:OSError: [Errno 22] Invalid argument: 'E:\\Downloads\\課程素材\\工作\test_data.csv'

-----------------------------------------------------------------------------------------------

最主要是最后一句:?

OSError: [Errno 22] Invalid argument: 'E:\\Downloads\\課程素材\\工作\test_data.csv'

前面復(fù)制的Windows文件夾路徑是\\, 后面文件名前面的是我自己加上的\, 提醒我可能是路徑格式問題.

根據(jù)參考網(wǎng)上查到一篇文章(見下),試了幾種方法:

1)? r'E:\Downloads\課程素材\工作\test_data.csv'? ? ?-----OK

2)??'E:\\Downloads\\課程素材\\工作\\test_data.csv'? -----OK

3)? r'E:\\Downloads\\課程素材\\工作\\test_data.csv'?-----OK

4)??r'E:\\Downloads\\課程素材\\工作\test_data.csv'? -----OK

5)??'E:/Downloads/課程素材/工作/test_data.csv'? ? ? ?-----OK

6)??r'E:/Downloads/課程素材/工作/test_data.csv'? ? ? -----OK

7)??r'E:\Downloads\\課程素材\/工作/test_data.csv'? ? -----OK

8)??'E:\Downloads\\課程素材\/工作/test_data.csv'? ? ?-----OK

9)??'E:\Downloads\\課程素材\/工作\/test_data.csv'? ? ?-----OK

10)?'E:\Downloads\\課程素材\/工作/\test_data.csv'? ? -----不行

11)??r'E:\Downloads\\課程素材\/工作/\test_data.csv'? ?-----OK


參考文獻:?

問題的根本:windows讀取文件可以用\,但在字符串里面\被作為轉(zhuǎn)義字符使用,那么python在描述路徑時有兩種方式:

'd:\\a.txt',轉(zhuǎn)義的方式

r'd:\a.txt'么夫,聲明字符串不需要轉(zhuǎn)義

這樣就實現(xiàn)了python在windows系統(tǒng)中用\來訪問,其實這樣比較麻煩的是不是,下面對幾種情況說明:

問題1:其實python中文件的絕對路徑可以直接復(fù)制window的路徑店乐,

如:

C:\Users\Administrator\Desktop\python\source.txt? 這個路徑是沒有問題的

但是,其實你的絕對路徑正確呻袭,但是執(zhí)行報錯眨八,那么就是你文件名的問題,如:

C:\Users\Administrator\Desktop\python\t1.txt? 這個路徑絕對會報錯左电,因為 \t被轉(zhuǎn)義了

python就會解析為 C:\Users\Administrator\Desktop\python 1.txt? 這個時候肯定會報錯的

若果你改成下面的寫法就不會報錯啦(推薦使用此寫法“/"廉侧,可以避免很多異常)

C:/Users/Administrator/Desktop/python/t1.txt

————————————————

版權(quán)聲明:本文為CSDN博主「講測試的古古奇老師」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議篓足,轉(zhuǎn)載請附上原文出處鏈接及本聲明段誊。

原文鏈接:https://blog.csdn.net/jusulysunbeamy/article/details/51290080


〇〇二:?

2022.1.6? 15:11

解決了路徑格式的問題, 從網(wǎng)上下載的示例csv可以打開了, 但是我從EXCEL表格轉(zhuǎn)出的csv還是報錯.

錯誤信息:?

---------------------------------------------------------------------------UnicodeDecodeErrorTraceback (most recent call last)E:\Temp/ipykernel_2916/486158148.pyin<module> 1importpandasaspd 2# 讀取練習(xí)數(shù)據(jù),文件路徑為'./工作/test_data.csv'栈拖,編碼格式為'utf-8'----> 3 test_data=pd.read_csv(r'I:\test_data.csv') 4# 查看 test_data 5test_datad:\program files\python37\lib\site-packages\pandas\util\_decorators.pyinwrapper(*args, **kwargs) 309stacklevel=stacklevel, 310)--> 311 returnfunc(*args,**kwargs) 312 313returnwrapperd:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyinread_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options) 584kwds.update(kwds_defaults) 585--> 586 return_read(filepath_or_buffer,kwds) 587 588d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin_read(filepath_or_buffer, kwds) 480 481# Create the parser.--> 482 parser=TextFileReader(filepath_or_buffer,**kwds) 483 484ifchunksizeoriterator:d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin__init__(self, f, engine, **kwds) 809self.options["has_index_names"]=kwds["has_index_names"] 810--> 811 self._engine=self._make_engine(self.engine) 812 813defclose(self):d:\program files\python37\lib\site-packages\pandas\io\parsers\readers.pyin_make_engine(self, engine) 1038) 1039# error: Too many arguments for "ParserBase"-> 1040 returnmapping[engine](self.f,**self.options)# type: ignore[call-arg] 1041 1042def_failover_to_python(self):d:\program files\python37\lib\site-packages\pandas\io\parsers\c_parser_wrapper.pyin__init__(self, src, **kwds) 67kwds["dtype"]=ensure_dtype_objs(kwds.get("dtype",None)) 68try:---> 69 self._reader=parsers.TextReader(self.handles.handle,**kwds) 70exceptException: 71self.handles.close()d:\program files\python37\lib\site-packages\pandas\_libs\parsers.pyxinpandas._libs.parsers.TextReader.__cinit__()d:\program files\python37\lib\site-packages\pandas\_libs\parsers.pyxinpandas._libs.parsers.TextReader._get_header()d:\program files\python37\lib\site-packages\pandas\_libs\parsers.pyxinpandas._libs.parsers.TextReader._tokenize_rows()d:\program files\python37\lib\site-packages\pandas\_libs\parsers.pyxinpandas._libs.parsers.raise_parser_error()UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 566: invalid start byte


最后一句提示可能是編碼的問題.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 566: invalid start byte

難道excle轉(zhuǎn)存的csv的默認編碼格式不是UTF-8? 谷歌一查, 還真是, 默認是ANSI. ( https://zhidao.baidu.com/question/2014606813258805588.html )

在剛才語句后面加上encoding = 'ANSI' , 就可以正確打開csv了.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末连舍,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子涩哟,更是在濱河造成了極大的恐慌索赏,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贴彼,死亡現(xiàn)場離奇詭異潜腻,居然都是意外死亡,警方通過查閱死者的電腦和手機器仗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門融涣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人精钮,你說我怎么就攤上這事威鹿。” “怎么了轨香?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵忽你,是天一觀的道長。 經(jīng)常有香客問我弹沽,道長檀夹,這世上最難降的妖魔是什么筋粗? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮炸渡,結(jié)果婚禮上娜亿,老公的妹妹穿的比我還像新娘。我一直安慰自己蚌堵,他們只是感情好买决,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著吼畏,像睡著了一般督赤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上泻蚊,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天躲舌,我揣著相機與錄音,去河邊找鬼性雄。 笑死没卸,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的秒旋。 我是一名探鬼主播约计,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼迁筛!你這毒婦竟也來了煤蚌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤细卧,失蹤者是張志新(化名)和其女友劉穎尉桩,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酒甸,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡魄健,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了插勤。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡革骨,死狀恐怖农尖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情良哲,我是刑警寧澤盛卡,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站筑凫,受9級特大地震影響滑沧,放射性物質(zhì)發(fā)生泄漏并村。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一滓技、第九天 我趴在偏房一處隱蔽的房頂上張望哩牍。 院中可真熱鬧,春花似錦令漂、人聲如沸膝昆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽荚孵。三九已至,卻和暖如春纬朝,著一層夾襖步出監(jiān)牢的瞬間收叶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工共苛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留滔驾,地道東北人。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓俄讹,卻偏偏與公主長得像哆致,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子患膛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容