File Input/Output – Python

This is the last part of the Python exercises on codecademy. It trains one on how to read information from a file on your computer, and/or write that information to another file. This process is called file I/O (the “I/O” stands for “input/output”).

I. Introduction to file I/O

i. See It to Believe It 1/9

>Simply save and submit!

ii. The open() Function 2/9

my_file = open(“output.txt”, “r+”)

iii. Writing 3/9

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

my_file = open(“output.txt”, “r+”)

# Add your code below!
for each in my_list:
return my_file.write(each) \n

my_file.close()

iv. Reading 4/9

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

II The Devil’s in the Details

i. Reading Between the Lines 5/9

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

my_file.close()

ii. PSA: Buffering Data 6/9

# 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
print read_file.read()
read_file.close()

iii. The ‘with’ and ‘as’ Keywords 7/9

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

iv. The ‘with’ and ‘as’ Keywords

Save and Submit

v. Try it Yourself

with open(“text.txt”,”w”) as my_file:
my_file.write(“You are and apple”)

vi. Case Closed?

with open(“text.txt”,”w”) as my_file:
my_file.write(“You are and apple”)
if my_file.closed == False:
my_file.close()
print my_file.closed


 

Congratulations!! You’re done.

 

Advertisements

3 thoughts on “File Input/Output – Python

  1. 3. Writing should be:

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

    my_file = open(“output.txt”, “r+”)

    # Add your code below!
    for each in my_list:
    my_file.write(str(each)+”\n”)

    my_file.close()

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s