簡體   English   中英

Python錯誤:FileNotFoundError:[Errno 2]沒有這樣的文件或目錄(read_csv打開)

[英]Python error: FileNotFoundError: [Errno 2] No such file or directory(read_csv with open)

with open('~/Documents/data.csv', 'r') as f:
    print(f.read())

data=pd.read_csv('~/Documents/data.csv')

當我使用第一個"with open"方法時,出現錯誤。 但是當我使用"read_csv"時沒有問題。

誰能告訴我為什么? 謝謝!

使用open() ,您必須使用os.path.expanduser()函數將波浪號~擴展到用戶的實際主目錄中:

import os
with open(os.path.expanduser('~/Documents/data.csv'), 'r') as f:
    print(f.read())

熊貓的read_csv()為您做到了。

(警告:由於~是Linux文件名中的有效字符,所以僅用os.getenv("HOME")替換~是一個非常糟糕的主意...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM