1
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!

5
  • 2
    Not all functions process the ~ in a path. Some just take it as a tilde. Commented Nov 9, 2018 at 4:16
  • What is the error with open gave? Commented Nov 9, 2018 at 4:17
  • The error is FileNotFoundError: [Errno 2] No such file or directory. Commented Nov 9, 2018 at 4:20
  • 1
    Try using the full path eg /home/<username>/Documents/data.csv or use a module like pathlib to expanduser(). Commented Nov 9, 2018 at 4:26
  • I have just modified the "~" to the full path, thank you! Commented Nov 9, 2018 at 4:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.