-1

I have a text file that contains State names and their corresponding Capital. I am trying to read the lines one at a time and separate the State from the Capital. Then I want to add the States and Capitals as key and value pairs in my dictionary respectively. I am still very new to programming so any help would be appreciated. Currently, I am struggling to separate the text file one line at a time. This is what I have so far.

def main():

    dict = {}
    file = open(input("Please enter the name of the file: "))
    lines = file.readline()

    while lines:
        text = lines.split(",")
        lines = file.readline()   

Example of Text File:

Arizona,Phoenix

Arkansas,Little Rock

California,Sacramento

Colorado,Denver

Connecticut,Hartford

Florida,Tallahassee

Georgia,Atlanta
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
chrisscartier
  • 101
  • 1
  • 1
  • 5
  • Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. "Show me how to solve this coding problem?" is off-topic for Stack Overflow. You have to make an honest attempt at the solution, and then ask a *specific* question about your implementation. Stack Overflow is not intended to replace existing tutorials and documentation. – Prune May 03 '21 at 23:04
  • You need to work through a tutorial on Python files; any of these will teach you how to iterate through the lines of a text file. – Prune May 03 '21 at 23:05
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Woodford May 03 '21 at 23:22

1 Answers1

1

Use the following example how to read the file and parse States and Capitals:

output = {}
with open("your_file.txt", "r") as f_in:
    for line in f_in:
        line = line.strip()
        if line == "":  # skip empty lines
            continue
        state, capital = line.split(",")
        output[state] = capital  # add state and capital to output dictionary

print(output)

Prints:

{'Arizona': 'Phoenix', 
 'Arkansas': 'Little Rock', 
 'California': 'Sacramento', 
 'Colorado': 'Denver', 
 'Connecticut': 'Hartford', 
 'Florida': 'Tallahassee', 
 'Georgia': 'Atlanta'}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91