3. Writing testing/create text.txt


#1



Code passes.Output says this : Traceback (most recent call last):
File "python", line 3, in
IOError: [Errno 2] No such file or directory: 'output.txt'


my_list = [i**2 for i in range(1,11)]

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

# Add your code below!
for item in range(1,11):
    my_file.write(str(item) + "\n")
    
my_file.close()


#2

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

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


#3
  1. Iterate over my_list to get each value

for item in my_list: replace range(1,11) in your code. There is no range to iterate through


#4

Also, as I found out the hard way. If you accidentally use /n instead of \n the first time, it will still print something in the txt file which you MUST DELETE before running the corrected code or you will continue to fail and not know why.


#5

this is the code that I have:
my_list = [i**2 for i in range(1,11)]

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

Add your code below!

for i in my_list:
my_file.write(str(i)+"\n")
my_file.close()

I cannot figure out what I am doing wrong. I've compared it with answers online and it matches, but the output gives me the response "Oops, try again. It looks like your file doesn't contain each element from my_list on its own line," with " , 81, 100]" on the eleventh line.