Often, your program needs to work with data in files - you don't want to make the user input a whole bunch of values every time they use it.
Examples:
Python provides a built-in open() function which will returns a new type with a scary name like _io.TextIOWrapper.
#assumes the gettysburg.txt file is in
#the same directory as your .py file
gettysburg_file = open("gettysburg.txt")
type(gettysburg_file)
For our purposes, just think of the variable gettysburg_file as a variable which represents a file object.
Python files work with several different methods that allow you to read data.
read() reads the file into a big stringreadline() reads the next line of the file into a stringreadlines() reads the lines of the file into a list of stringsgettysburg_file = open("gettysburg.txt")
file_contents = gettysburg_file.read()
print(file_contents)
gettysburg_file = open("gettysburg.txt")
firstline = gettysburg_file.readline()
secondline = gettysburg_file.readline()
print(secondline)
gettysburg_file = open("gettysburg.txt")
contents_as_list = gettysburg_file.readlines()
print( contents_as_list[8] )
with statements¶Opening files with a with statement does the same thing, but it does some nice things like closing the file when it is done.
with open("gettysburg.txt") as gettysburg_file:
gettysburg_text = gettysburg_file.readlines()
print(gettysburg_text)
print("All done with the file.")
Let's say we want to analyze baby name popularity, and we have a file with data from https://www.ssa.gov/oact/babynames/decades/names2010s.html
with open("top_male_baby_names_2010s.txt") as male_names_file:
male_names = male_names_file.readlines()
print(male_names)
It's annoying that the newline character \n is included in all of the strings. To remove these, you could use the rstrip() string method.
name = "Eric\n"
name
name.rstrip()
with open("top_male_baby_names_2010s.txt") as male_names_file:
male_names = male_names_file.readlines()
name_counter = 0
while name_counter < len(male_names):
male_names[name_counter] = male_names[name_counter].rstrip()
name_counter += 1
print(male_names)
Here's a program that lets the user check how popular a name was.
name_to_search = input("Enter a name: ")
if name_to_search in male_names:
position = male_names.index(name_to_search)
print(name_to_search,"was the number",(position+1),"most popular male name in the 2010s.")
else:
print(name_to_search,"was not a popular name in the 2010s.")