156k views
4 votes
Python lab reading strings from a file: prompt the user for the name of the file, read in a list of states from the file?

User OGHaza
by
7.6k points

1 Answer

4 votes

Final answer:

To read in a list of states from a file in Python, you can prompt the user for the name of the file and use the 'open' function to read the file contents. Then, you can process the lines of the file to create a list of states.

Step-by-step explanation:

To prompt the user for the name of the file and read in a list of states from the file in Python, you can use the following code:

filename = input('Enter the name of the file: ') # Prompt the user for the filename

try:
with open(filename, 'r') as file:
states = file.readlines() # Read all lines from the file
states = [state.strip() for state in states] # Remove newline characters
print(states) # Print the list of states
except FileNotFoundError:
print('File not found!')

User DirkNM
by
7.7k points