0

HowTo Read File in Python Interpreter?

I want to

f = open("~/jobs/2014-12-16/output/output.log", "r")

in Python interactive Shell. How?

Getting:

IOError: [Errno 2] No such file or directory: '~/jobs/2014-12-16/output/output.log'

Without path it works if Interpreter started in parent working directory.

1

2 Answers 2

1

There's no (well, very little) difference between interactive python and non-interactive python. Your problem is that the file does not exist, as stated in the error message. Python does not automatically expand the ~ character in paths, you have to use the os.path.expanduser function for that.

f = open(os.path.expanduser("~/jobs/2014-12-16/output/output.log"), "r")
Sign up to request clarification or add additional context in comments.

Comments

1

You need to tell Python to deference the ~ character via os.path.expanduser.

full_path = os.path.expanduser("~/jobs/2014-12-16/output/output.log")
f = open(full_path, 'r')

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.