My program cannot find the text.txt file


#1


#2

@adorevip,

With
my_file = open("text.txt","r")

you are trying to open an existing file.....in read modus.....
If you use following code
you will see which files are available....

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)
#my_file.close()

===============================================

You could use the following code to create a new text.txt file....

import os
print "== if the file doesn't exist, create one =="
if os.path.exists('text.txt'):
    print "File exists"
else:
    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.close()

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

Reference:
== discussions / opinions ==
http://stackoverflow.com/questions/11968976/list-files-in-only-the-current-directory
http://stackoverflow.com/questions/18533621/creating-a-new-text-file-with-python
http://stackoverflow.com/questions/5214578/python-print-string-to-text-file


Lesson 5 Someone Pl help to get through this lesson
What is the problem with following code?
#3

but accroding to the instruction, the file "text.txt" had been created; I just want to open it.


#4

ok, i made it run with your code, thank you very much!


#5

I also had this problem. i didn't use the if statement and the else statement. I tried with them,it worked


#6

Thanks so much :rose: :rose: :rose: :rose: :rose: :rose: :rose::rose: :rose:


#7

lol that was beautiful.


#8

Thank you for this contribution but I feel that trying to open existing files is outside the scope of the lessons I have received so far in the python course. I ran into the same problem, your contribution however pointed me to the fact that the error is there because we are trying to read from a file that does not exist.

Ordinarily, I thought that would be handled for us but this is how I think the problem could be solved:

  1. Create the list using the list comprehension

  2. Open the text file in write mode, iterate over the list and write the content into the file, line by line.

  3. Close the file

  4. Now go ahead and read from the text file with the three read line statements, then close the file.

I hope this helps.