简体   繁体   中英

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')

when I used the first "with open" method, I got an error. But there is no problem when I use the "read_csv" .

So could anyone tell me why? Thank you!

With open() , you have to use the os.path.expanduser() function to expand the tilde ~ into the actual home directory of the user:

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

Pandas' read_csv() does that for you.

(A word of warning: since ~ is a valid character in Linux filenames, just replacing ~ with os.getenv("HOME") is a very bad idea...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM