Week 6 File I/O - CS50's Introduction to Programming with Python
Up until now, everything we’ve programmed has stored information in memory. That is, once the program is ended, all information gathered from the user or generated by the program is lost.
File I/O is the ability of a program to take a file as input or create a file as output.
To begin, in the terminal window type code names.py
and code as follows:
name = input("What's your name?" ) print(f"hello, {name}")
Notice that running this code has the desired output. The user can input a name. The output is as expected.
However, what if we wanted to allow multiple names to be inputted? How might we achieve this? Recall that a list
is a data structure that allows us to store multiple values into a single variable. Code as follows:
`names = []
for _ in range(3): name = input("What's your name?" ) names.append(name)`
Notice that the user will be prompted three times for input. The append
method is used to add the name
to our names
list.
This code could be simplified to the following:
`names = []
for _ in range(3): names.append(input("What's your name?" ))`
Notice that this has the same result as the prior block of code.
`names = []
for _ in range(3): names.append(input("What's your name?" ))
for name in sorted(names): print(f"hello, {name}")`
Notice that once this program is executed, all information is lost. File I/O allows your program to store this information such that it can be used later.
You can learn more in Python’s documentation of sorted.
open
open
is a functionality built into Python that allows you to open a file and utilize it in your program. The open
function allows you to open a file such that you can read from it or write to it.
To show you how to enable file I/O in your program, let’s rewind a bit and code as follows:
`name = input("What's your name? ")
file = open("names.txt", "w") file.write(name) file.close()`
Notice that the open
function opens a file called names.txt
with writing enabled, as signified by the w
. The code above assigns that opened file to a variable called file
. The line file.write(name)
writes the name to the text file. The line after that closes the file.
Testing out your code by typing python names.py
, you can input a name and it saves to the text file. However, if you run your program multiple times using different names, you will notice that this program will entirely rewrite the names.txt
file each time.
Ideally, we want to be able to append each of our names to the file. Remove the existing text file by typing rm names.txt
in the terminal window. Then, modify your code as follows:
`name = input("What's your name? ")
file = open("names.txt", "a") file.write(name) file.close()`
Notice that the only change to our code is that the w
has been changed to a
for “append”. Rerunning this program multiple times, you will notice that names will be added to the file. However, you will notice a new problem!