Codecademy Python Answers File input and Output

 Also Read : How to chat with your friend on command prompt

File input/output 1/9 – See To Believe It

my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list:
    f.write(str(item) + "\n")

f.close()

File input/output 2/9 – The Open() Function

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

File input/output 3/9 – Writing

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()

File input/output 4/9 – Reading

my_file = open("output.txt","r")
print my_file.read()
my_file.close()

File input/output 5/9 – Reading Between the Lines

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

File input/output 6/9 – PSA:Buffering Data

# Open the file for reading
read_file = open("text.txt", "r")

# Use a second file handler to open the file for writing
write_file = open("text.txt", "w")
# Write to the file
write_file.write("Not closing files is VERY BAD.")

write_file.close()


# Try to read from the file
read_file.close()
print read_file.read()

File input/output 7/9 – The ‘with’ and ‘as’ Keywords

with open("text.txt", "w") as textfile:
	textfile.write("Success!")

File input/output 8/9 – Try it yourself

with open("text.txt","r+") as f:
    f.write("hello world")
    f.read()

File input/output 9/9 – Case closed

with open("text.txt","r+") as f:
    f.write("hello world")
    if f == f.closed:
        f.close()
print f.closed

Leave a Reply

Your email address will not be published. Required fields are marked *