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()
== discussions / opinions ==
Lesson 5 Someone Pl help to get through this lesson
What is the problem with following code?
but accroding to the instruction, the file “text.txt” had been created; I just want to open it.
ok, i made it run with your code, thank you very much!
I also had this problem. i didn’t use the if statement and the else statement. I tried with them,it worked
Thanks so much
lol that was beautiful.
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:
Create the list using the list comprehension
Open the text file in write mode, iterate over the list and write the content into the file, line by line.
Close the file
Now go ahead and read from the text file with the three read line statements, then close the file.
I hope this helps.