In: Computer Science
22.34 Lab 12 B FALL 2019 Python File I/O demo
Overview
This is a demonstration of File IO
Description
Read in a list of states from a file, and output those states in alphabetical order.
Provided input files
A single input file named states.txt is provided that lists the 50 states of the United States - one state per row. Some states have lowercase letters, where some begin with uppercase letters. As a reminder, lowercase letters come after uppercase letters alphabetically. The states are in a random order. The file has the following format:
Michigan Alaska New Mexico Alabama Nevada ...
Objectives
Write the following in main.py:
Alabama Alaska Arizona ...
The file is created as states.txt name.
states.txt -
Michigan
Alaska
New Mexico
Alabama
Nevada
Montana
Nebraska
New Hampshire
New Jersey
minnesota
arkansas
california
colorado
connecticut
delaware
florida
georgia
hawaii
idaho
illinois
indiana
iowa
kansas
kentucky
louisiana
maine
maryland
massachusetts
michigan
mississippi
montana
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
missouri
nevada
new Hampshire
new Jersey
arizona
new York
north Carolina
north Dakota
ohio
nebraska
west Virginia
oregon
pennsylvania
rhode Island
south Carolina
oklahoma
south Dakota
tennessee
texas
utah
vermont
virginia
washington
new Mexico
wisconsin
wyoming
alabama
alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Minnesota
Mississippi
Missouri
Then, in the program, a list is created with the name states.
All the content from the text file is printed to the user.
Program –
main.py –
states = [] # an empty list to store the name of the states # opening a tetx file with open("states.txt") as f: for ff in f: # takiing the elements from the text file to the list states.append(ff) # sorting the list states = sorted(states) # displaying the name of the states for i in states: print(i)
Sample output –
Explanation –