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.

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • 1
    I don't think `~` works here, see: http://stackoverflow.com/questions/4028904/how-to-get-the-home-directory-in-python – chrki Jan 22 '15 at 10:55

2 Answers2

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")
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
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')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895