我是 python 和 pandas 庫的新手,我正面臨這個問題:Python 的 pandas 庫找不到我要打開的檔案,即使它與腳本位于同一目錄中。直到昨天,我還在使用 pandas 并使用相同的代碼行,并且運行良好,所以我很困惑。我可以從 CMD 視窗正常運行腳本,但不能從 Jupyter Lab 或 VSCode 運行。這是我的代碼:
from pandas import *
london = read_csv('London_2014.csv')
print(london.head())
這是我得到的錯誤串列:
Traceback (most recent call last):
File "c:\Users\Lautte\Desktop\PY\OPEN UNIVERSITY\Learn-to-code-for-data-analysis-master\2_Cleaning_up_our_act\test2.py", line
3, in <module>
london = read_csv('London_2014.csv')
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
return _read(filepath_or_buffer, kwds)
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 575, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 933, in __init__
self._engine = self._make_engine(f, self.engine)
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 1217, in _make_engine
self.handles = get_handle( # type: ignore[call-overload]
File "C:\Users\Lautte\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\common.py", line 789, in get_handle
handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'London_2014.csv'
提前感謝您,祝您度過愉快的一周!
uj5u.com熱心網友回復:
幾個初學者技巧。不要進行明星匯入,它們被認為是不好的做法,只需執行 pd.WhatYouWant 即 pd.read_csv。其次,它可以在 CMD 中作業,因為作業目錄與腳本相同,但不是來自 vscode,因為您可能沒有正確地將終端目錄更改為存放腳本和 csv 檔案的檔案夾。您可以使用絕對路徑而不是相對路徑,例如:london = read_csv("""c:\Users\Lautte\Desktop\PY\OPEN UNIVERSITY\Learn-to-code-for-data-analysis-master\2_Cleaning_up_our_act\London_2014. csv""") 應該可以在任何地方作業。
uj5u.com熱心網友回復:
您可以查看此檔案:- https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
或者可能是您為檔案提供了錯誤的名稱,或者您當前的作業目錄中沒有該檔案。
uj5u.com熱心網友回復:
London_2014.csv目錄里還有嗎?
你也可以試試:
import pandas as pd
london = pd.read_csv('./London_2014.csv')
print(london.head())
或將檔案的絕對檔案路徑傳遞London_2014.csv給pd.read_csv
uj5u.com熱心網友回復:
你可以像這樣重寫你的代碼
import pandas as pd
london = pd.read_csv('London_2014.csv')
print(london.head())
并且不要使用from pandas import *
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424762.html
