Help with Reading a File


I thought I understood what I was doing here, but my code was rejected with the error message: "Did you create a variable called my_file?."
However, in the console is says: "Traceback (most recent call last): File "python", line 1, in IOError: [Errno 2] No such file or directory: 'output.txt' "

Below is what I have for my code. Where am I going wrong?

my_file = open("output.txt", "r")


The Python-error-message "No such file or directory"
points to the fact

  • either the file does not exist
    If you use following code
    you will see which files are available....
    and will create the text.txt

import os
print "==show us the existing files =="
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    print str(f)

and if it doesn't exist you create the file

import os
print "== if the file doesn't exist, create one =="
if os.path.exists('text.txt'):
    print "File exists"
    print "Creating the text.txt-file"
    my_file = open("text.txt", 'w')
    my_file.write("I'm the first line of the file!" +"\n")
    my_file.write("I'm the second line."+"\n")
    my_file.write("Third line here, boss."+"\n")

my_file = open("text.txt","r")
print my_file.readline()
print my_file.readline()
print my_file.readline()

== discussions / opinions ==