0

I'm going through the "Learn python the hard way". It suggest running python from the terminal and using the open and read commands on a file.

I created the provided script and sample text file, and the script runs fine, no errors. But I cannot figure out how to open and read the file from within python.

I always get ex15_sample.txt is not defined. I am running python in the terminal from within the same folder that the script and text file are saved in. Within the script I do not give a file path, and I cannot figure where I'm going wrong?

I've tried:

open(ex15_sample.txt) # no go
open(filepath/ex15_sample.txt) # nope
file = open(ex15_sample.txt) # nope
open ex15_sample.txt # nope
print ex15_sample.txt.read() # nope
open(ex15_sample.txt, read) # nope.

I cannot figure this one out, can any provide any insight?

1

I managed to figure out what the answer is.

I was simply missing the quote marks. I didn't realise I needed to turn the filename into a string to be able to open it.

I was simply under the impression that input was automatially treated as a string value.

file = open('ex15_sample.txt') - opens and stores in file print file.read() - prints file to read contents

  • The quote marks weren’t always there... in early versions of python, they were unnecessary. but now... – j0h Aug 10 '15 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.